Open2
TypeScriptでブランド型からタグつきユニオンを作るユーティリティ型
type Brand<K, T extends string> = K & { __brand: T };
type ToTagged<B extends Brand<unknown, string>> = B extends Brand<
unknown,
infer T
>
? {
type: T;
value: B;
}
: never;
type A = Brand<number, 'A'>;
type B = Brand<string, 'B'>;
type AB = ToTagged<A | B>; // { type: 'A', value: A } | {type: 'B', value: B }