TypeScript の ブランド型
レベル 5393 打鍵
ブランド型は TypeScript の構造的型システムに名前的型付けを持ち込みます。UserId と OrderId はどちらも string ですが、一方が求められる場所にもう一方は渡せません。
TypeScript のコード
// T に型だけの目印 __brand を付ける1type Brand<T, B> = T & { __brand: B };// ブランドが違うので、この2つの string 型は互換性がない2type UserId = Brand<string, "UserId">;3type OrderId = Brand<string, "OrderId">;// ただの文字列を UserId に変えるファクトリー4function createUserId(id: string): UserId { // 型アサーションだけで、実行時には何も追加されない5 return id as UserId;6}// UserId だけを受け付ける。ただの文字列や OrderId はコンパイルできない7function getUser(id: UserId): void {8 console.log(`Fetching user: ${id}`);9}10const userId = createUserId("user_123");// as で直接ブランドを付けることもできる11const orderId = "order_456" as OrderId;// 「Fetching user: user_123」を表示する12getUser(userId);// 実行時は普通の文字列。「Order: order_456」を表示する13console.log(`Order: ${orderId}`);実行結果
Fetching user: user_123 Order: order_456
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
;× 9"× 8:× 7(× 6)× 6{× 5}× 5=× 5_× 4`× 4