1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TyeScript】never型を使った網羅性チェック

Posted at

はじめに

この記事では、TypeScript の never型を使った網羅性チェックについて記載します。
網羅性チェックとは、ロジックがすべてのパターンを網羅しているかをコンパイラにチェックさせることです。

なお、never型の概要については、別途以下の記事で記載しています。

never型を使った網羅性チェック

ユニオン型の分岐処理時、default に never型を使って網羅性チェックができます。

sample.ts
type PaymentMethod =
  | { type: "credit_card"; cardNumber: string }
  | { type: "paypal"; email: string }
  | { type: "bank_transfer"; accountNumber: string };

上記のユニオン型の2パターンのみ対応した分岐処理の default に never型を使うとエラーになります。

sample.ts
function processPayment(method: PaymentMethod): string {
  switch (method.type) {
    case "credit_card":
      return `Processing credit card payment for card: ${method.cardNumber}`;
    case "paypal":
      return `Processing PayPal payment for email: ${method.email}`;
    default:
      // Exhaustive check using never
      const _exhaustive: never = method;
      throw new Error(`Unhandled payment method: ${_exhaustive}`);
  }
}

image.png

エラーが出ることで網羅性がないことに気がつくことができます。

image.png

never型を使わないと、網羅性がなくてもエラーになりません。

image.png

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?