🤑

TS4.9の新機能で網羅性チェックを簡単に!「satisfies」を使ってみたら驚きの効果が!

2024/06/28に公開

どーも駆け出しエンジニアです。

TS4.9 で導入された satisfies を使えば以下のように網羅性チェックできることに気づきました!!!すごい???

type Color = "red" | "blue" | "green"

const color: Color = "red"

function isRed(color: Color): boolean {
  switch(color) {
    case "red": {
      return true;
    }
    case "blue": {
      return false;
    }
    case "green": {
      return false;
    }
    default: {
      return color satisfies never;
    }
  }
}

「satisfies」を使うことでスイッチ文の網羅性チェックがめちゃくちゃ簡単になって、コードの読みやすさも格段にアップしました。

べんりーーーーーーーーーー

Discussion