LoginSignup
5
1

More than 1 year has passed since last update.

TypeScript 4.9 の "satisfies" 演算子で union の網羅性チェックが少し楽になる

Posted at

TypeScript 4.9 で新たに導入される satisfies 演算子にとても期待しています。個人的に役に立ちそうだと思ったユースケースとして、switch や if で union を順番に処理していくときの網羅性チェックが挙げられます。

declare const difficulty: "easy" | "medium" | "hard";

switch (difficulty) {
    case "easy":
    case "medium":
    case "hard":
        break;
    default:
        // OK
        throw new Error(difficulty satisfies never);
}

switch (difficulty) {
    case "easy":
    case "hard":
        break;
    default:
        // Type 'string' does not satisfy the expected type 'never'.
        throw new Error(difficulty satisfies never);
}

1 つ目の switch 文ではエラーが出ませんが、2 つめの switch 文では "medium" を忘れているためエラーになります。

TypeScript 4.8 以前は次のように書いていました。

switch (difficulty) {
    case "easy":
    case "hard":
        break;
    default:
        // Type 'string' is not assignable to type 'never'.
        const _: never = difficulty;
        throw new Error(difficulty);
}

なお TypeScript ESLint の switch-exhaustiveness-check が使える環境ではそちらを使うほうがよさそうですが、switch 文以外で使う場合など、この記法が役に立つ場合も多いかと思います。

5
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
5
1