≪ Today I learned. RSS購読
公開日
タグ
TypeScript
著者
ダーシノ(@bc_rikko)

TypeScript 4.9 satisfies演算子

TypeScript 4.9 betasatisfies演算子が導入された。

Before

const palette = {
  red: [255, 0, 0],
  green: '#00ff00',
  bleu: [0, 0, 255]  // ← typo: blueが正解
}

// palette.red は number[] なので `Array#at()` が使える
const r = palette.red.at(0)

// palette.green は string なので `String#toUpperCase()` が使える
const g = palette.green.toUpperCase()

typoを帽子するために、Union Literal Typeを使っても問題がある。

type Colors = 'red' | 'green' | 'blue'
type RGB = [r:number, g:number, b:number]
// Record<K, V> でオブジェクトの key を制限できるので typo防止になる
const palette: Record<Colors, RGB | string> = { ... }

// Error: Record<Colors, RGB | string> があるので palette.red は (number[] | string)型になり `Array#at()` が使えない
const r = palette.red.at(0)

// Error: Record<Colors, RGB | string> があるので palette.green は (number[] | string)型になり `String#toUpperCase()` が使えない
const g = palette.green.toUpperCase()

After: satisfies演算子が登場

const palette = {
  red: [255, 0, 0],
  green: '#00ff00',
  blue: [0, 0, 255]
} satisfies Record<Colors, RGB | string>

このようにして、as constRecord<K, V>のいいとこどりができるようになった。