Создание t.or()
Как и все другие типы, t.or()
сделан c использованием customType()
, так что мы можем повторить его реализацию сами. Обратите внимание, что это потребует более глубокого понимания JavaScript и Typescript.
import { TCustomType, customType } from "encodexx";
// Извлекаем тип из TCustomType. К примеру `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){ // читаем тэг и по нему находим тип const index = buff.readUint8(); return types[index].decode(buff); }, encode(val, buffer) { // Находим тип среди тех, что получили в 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]> { // Если хотя бы 1 тип из переданных подходит, то t.or подходит return types.some((el) => el.guard(data)); }, name: `Or<${types.map((el) => el.name).join("|")}>`, });}
Тип работает также, как и оригинальный t.or()