0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

uniqueな型を作成するutility type (Branded)

Posted at

はじめに

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")

結論

アサーション必須!!?😊

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?