Open2

TypeScriptでブランド型からタグつきユニオンを作るユーティリティ型

Nakano as a ServiceNakano as a Service
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;
Nakano as a ServiceNakano as a Service
type A = Brand<number, 'A'>;
type B = Brand<string, 'B'>;

type AB = ToTagged<A | B>; // { type: 'A', value: A } | {type: 'B', value: B }