import { type Closure } from "@"; /** * ***Brief*** * Utility type for creating branded types with a unique string literal identifier `T1`. * * ***Example*** * ```ts * type Foo = * & BrandedStruct<"Foo"> * & { * foo: void; * }; * * type Bar = * & BrandedStruct<"Bar"> * & { * foo: void; * }; * * let union: Foo | Bar; * if (union.type === "Foo") { * /// ... * } * ``` */ export type BrandedStruct = { /** * ***Brief*** * Type-level marker specifying the unique type identifier `T1`. * * ***Example*** * ```ts * type Foo = * & BrandedStruct<"Foo"> * & { * foo: void; * }; * * type Bar = * & BrandedStruct<"Bar"> * & { * foo: void; * }; * * let union: Foo | Bar; * if (union.type === "Foo") { * /// ... * } * ``` */ type: T1; }; export namespace BrandedStruct { export type Task = Closure<[value: BrandedStruct], void>; export type Handler = { match(unknown: unknown): unknown is BrandedStruct; match(unknown: unknown, task: Task): unknown is BrandedStruct; match(unknown: unknown, brand: T1): unknown is BrandedStruct; match(unknown: unknown, brand: T1, task: Task): unknown is BrandedStruct; }; export const Handler: Handler = (() => { /** @constructor */ { return { match }; } function match(unknown: unknown): unknown is BrandedStruct; function match(unknown: unknown, task: Closure<[item: BrandedStruct], void>): unknown is BrandedStruct; function match(unknown: unknown, brand: T1): unknown is BrandedStruct; function match(unknown: unknown, brand: T1, task: Closure<[item: BrandedStruct], void>): unknown is BrandedStruct; function match( p0: unknown, p1?: Task | T1, p2?: Task ): p0 is BrandedStruct { let unknown: unknown = p0; if (!_valid(unknown)) return false; if (typeof p1 === "string") { let brand: T1 = p1; if (!_valid(unknown, brand)) return false; } let value: BrandedStruct = (unknown as BrandedStruct); if (typeof p1 === "function") { let task: Task = p1; task(value); return true; } if (typeof p2 === "function") { let task: Task = p2; task(value); return true; } return true; } function _valid(unknown: unknown): unknown is BrandedStruct; function _valid(unknown: unknown, brand: T1): unknown is BrandedStruct; function _valid( p0: unknown, p1?: T1 ): p0 is BrandedStruct { let unknown: unknown = p0; if (!( unknown !== null && unknown !== undefined && typeof unknown === "object" && "type" in unknown && typeof unknown.type === "string" )) return false; if (p1 && unknown.type !== p1) return false; return true; } })(); }