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

TypeScript のレベル 5 のほかのコード例

← TypeScript タイピング練習のトップへ