TypeScriptで幽霊型を使う
metadataをもう少し加える
実装
{unique symbol: never}
確実に被らなくなる
{unique symbol: string}
$ declare const tag: unique symbol; type Branded<T, Tag> = T & { tag: Tag } Tagにuniqueな文字列を入れる必要がある
type Branded<T, Tag> = T & {[key in Tag]: never}
def1.ts.def2.tsの簡易版
unique symbol不使用
code:def1.ts
export type Branded<T, Tag extends string> = T & { [key in __PT__${Tag}]: never };
code:def2.ts
export type Branded<T, Name extends string> = T & { [key in __${Name}]: typeof tag };
declare const tag: unique symbol;
複数のBranded typesを組み合わせられるようにしてある
code:ts
declare const brand: unique symbol;
code:a@0.1.0.ts
declare const tag: unique symbol;
export type Branded<T, Name extends string> = T & { [key in __${Name}]: typeof tag };
code:a@0.2.0.ts
declare const tag: unique symbol;
export type Branded<T, Name extends string> = T & { [key in __${Name}]: typeof tag };
code:main-1.ts
import type { Branded } from "./a@0.1.0.ts";
import type { Branded as Branded2 } from "./a@0.2.0.ts";
const a = 34 as Branded<number, "pointer">;
// @ts-expect-error
const b: Branded2<number, "pointer"> = a;