プリミティブ型と存在しないプロパティを交差型で定義する事で、 string を代⼊しようと すると型的にエラーになる⼀⽅、 string として扱える型が作れる。 type Raw = string & { __brand: "Raw" }; const raw: Raw = "password"; // Error // Type 'string' is not assignable to type '{ __brand: "Raw"; }' const raw: Raw = "password" as Raw; const identity = (text: string) => text; identity(rawPassword); Branded Type というテクニック
ジェネリクスを使ったりして整理するとこんな感じにできる declare const __brand: unique symbol type Brand = { [__brand]: B }; export type Branded = T & Brand; type Raw = Branded; 参考⽂献: Improve Runtime Type Safety with Branded Types in TypeScript | egghead.io Branded Type というテクニック