Functions for Creating Types
A function wrapper allows you to utilize closures when creating custom types, opening up a wide range of possibilities.
Usage Examples
- Adding a Tag
import { customType } from "encodexx"
export function strWithTag(tag: string) { return customType<string>({ encode(buffer, str) { buffer.writeString(tag + str); }, decode(buffer) { return buffer.readString(); }, guard(data) { return typeof data === "string"; }, name: "stringWithTag " + tag, });}
import { Serializer } from "encodexx"
import { strWithTag } from "./str-with-tag.ts"
const serializer = new Serializer({ name: strWithTag("Dr. ")})
const encoded = serializer.encode({ name: "House"})
console.log(serializer.decode(encoded)) // {name: "Dr. House"}
Caution
For proper schema comparison in the .equal()
method, you must use a unique name for each distinct type. In this example, we append the tag to the type name.
- Using type or t.none
import { customType, TConvertValueToType } from "encodexx"
export function orNone<T extends TSchema>(type: T) { if (TYPE_SYMBOL in type) return t.or(t.none, type); return t.or(t.none, t.schema(type));}
What’s Next?
For a more advanced example of using functions to create types, check out the examples.