Skip to main content
On this page

Creating t.or()

Just like all other types, t.or() is implemented using customType(), so we can replicate its implementation ourselves. Note that this will require a deeper understanding of JavaScript and TypeScript.

my-or.ts
import { TCustomType, customType } from "encodexx";
// Extract the type from TCustomType. For example, TCustomType<number | string> -> number | string
type ExtractCustomType<T extends TCustomType> = T extends TCustomType<infer R> ? R : never;
export function myOr<T extends TCustomType[]>(...types: T) {
if (types.length > 255) throw new Error("Too many types provided: Maximum allowed is 255");
return customType<ExtractCustomType<T[number]>>({
decode(buff) {
// Read the tag and use it to determine the type
const index = buff.readUint8();
return types[index].decode(buff);
},
encode(val, buffer) {
// Find the corresponding type among the provided types
const typeIndex = types.findIndex((el) => el.guard(val));
if (typeIndex === -1) throw new Error("No matching type found among the provided types");
buffer.writeUint8(typeIndex);
types[typeIndex].encode(buffer, val);
},
guard(data): data is ExtractCustomType<T[number]> {
// t.or applies if at least one of the provided types matches
return types.some((el) => el.guard(data));
},
name: `Or<${types.map((el) => el.name).join("|")}>`,
});
}

The type works the same as the original t.or()