型表現に使われる演算子

typeof 演算子

通常の式では渡された値の型の名前を文字列として返すが、

<aside> 💡 型のコンテキストで用いると変数から型を抽出してくれる

</aside>

console.log(typeof 100); // 'number'

const arr = [1, 2, 3];console.log(typeof arr); // 'object'

type NumArr = typeof arr;

const val: NumArr = [4, 5, 6];

const val2: NumArr = ['foo', 'bar', 'baz']; // compile error!

in 演算子

通常の式では指定した値がオブジェクトのキーとして存在するかどうかの真偽値を返したり、for...in 文ではオブジェクトからインクリメンタルにキーを抽出する

<aside> 💡 型コンテキストでは、列挙された型の中から各要素の型の値を抜き出してマップ型(Mapped Types)というものを作る

</aside>

type Keys = 'x' | 'y';
type Flags = { [K in Keys]: boolean };

const flag: Flags = {
  x: true,
  y: false,
};

keyof演算子

<aside> 💡 オブジェクトの型からキーを抜き出してくるもの

</aside>

const permissions = {r: 0b100,w: 0b010,x: 0b001,};

type PermsChar = keyof typeof permissions; // 'r' | 'w' | 'x'

// valueof演算子の代わりとなる[]演算子

type PermsNum = typeof permissions[PermsChar]; // 1 | 2 | 4

Constアサーション

<aside> 💡 定数としての型注釈を付与するもの

</aside>

const permissions = {
	r: 0b100,
	w: 0b010,
	x: 0b001,
} as const;