LoginSignup
1
1

More than 1 year has passed since last update.

TypeScript opaque type

Last updated at Posted at 2022-12-03

TypeScriptでidなどを扱う際に意図せず値を代入することがないように型をつけることができる。

const idKey: unique symbol = Symbol();
type ID = string & { [idKey]: 'IDENTIFIER' };

このようにすることで
ID型 → string型 の代入はできて
string型 → ID型 はできないような型が定義できる。(ID型の実体はただのstring型)

string型をID型として扱うには

function g_ID(x: string): ID {
  return x as ID;
}

こうする。

C++とかでよく使われるらしい。

こんな書き方もあった

declare const idKey: unique symbol;
type ID = string & { [idKey]: never };
1
1
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
1
1