TypeScript の 型安全のためのブランド型
レベル 5432 打鍵
ブランド型は string に見せかけの __brand プロパティを付け加えるので、実行時はどちらも文字列でも UserId と OrderId を取り違えられなくなります。
TypeScript のコード
// 基底型 K とコンパイル時だけの目印 T を交差させる1type Brand<K, T> = K & { __brand: T };// どちらも string だが、ブランドが違うので互換性がない2type UserId = Brand<string, "UserId">;3type OrderId = Brand<string, "OrderId">;// ただの string から UserId を得るための唯一の想定された方法4function createUserId(id: string): UserId { // as は型を変えるだけで、実行時は同じ文字列のまま5 return id as UserId;6}// OrderId 用の同様のファクトリー7function createOrderId(id: string): OrderId {8 return id as OrderId;9}// UserId だけを受け付ける。orderId やただの文字列を渡すとコンパイルエラー10function getUser(id: UserId): void {11 console.log(`Getting user: ${id}`);12}13const userId = createUserId("user-123");// 対比のためだけに作る。getUser(orderId) はコンパイルできない14const orderId = createOrderId("order-456");// 正しい型なので「Getting user: user-123」を表示する15getUser(userId);実行結果
Getting user: user-123
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
;× 9:× 8"× 8(× 7)× 7{× 5}× 5=× 5,× 3<× 3