はじめに
idが複数ある時に、型でどのidなのか区別できるようにしたい。
その解決策メモ
問題点
type PrivateID = string;
type PublicID = string;
const privateID: PrivateID = "1";
const publicID: PrivateID = "1";
const func = (id: PrivateID) => {}
func(publicID) // ok
const PrivateIDArray = [privateID]
PrivateIDArray.includes(publicID) // ok
解決策
Branded typeを作成
type Branded<T, U> = T & { __brand: U }
type PrivateID = Branded<string, "PRIVATE_ID">
type PublicID = Branded<string, "PUBLIC_ID">
const privateID = "1" as PrivateID;
const publicID = "1" as PublicID;
const func = (id: PrivateID) => {}
func(publicID) // error
const PrivateIDArray = [privateID]
PrivateIDArray.includes(publicID) // error
おまけ
// 普通に書いても良さそう
type ID = string & "ID"
// リテラル型のみにすると他の型全てと区別できそう (stringやnumberのメソッドが使えなくなる)
type ID = "ID"
const id = 1 as unknown as ID
// 関数
type Branded<T, U> = T & { __brand: U }
const applyBrand = <T, U extends string>(value: T) => {
return value as Branded<T, U>
}
const id = applyBrand<string, "ID">("1")
結論
アサーション必須!!?😊