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?

More than 1 year has passed since last update.

TypeScriptのnever 型について

1
Last updated at Posted at 2023-09-09

never とは?

never は TypeScript の特殊な型の一つで、関数が決して正常に終了しないことを示す型です。具体的には、以下のような場面で never 型が使用されることが一般的です

  • 関数が常にエラーをスローする。
  • 関数が終了しない(例えば、無限ループ)。

never 型の例

常に例外をスローする関数

function throwError(message: string): never {
    throw new Error(message);
}

無限ループを持つ関数

function infiniteLoop(): never {
    while (true) {}
}

never の利用ケース

never 型は、他の型と組み合わせることで、コードの厳密な型チェックを強化するためにも使用されます。例えば、網羅的なチェックを行う場合などです。

以下は、never を使用して網羅的なチェックを行う例です:

// `Shape` という型を定義。
// この型は `circle` または `square` のどちらかの形状を持つことを示しています。
type Shape = 
    | { kind: 'circle', radius: number } // 円の場合、`radius`(半径)を持つ
    | { kind: 'square', sideLength: number }; // 正方形の場合、`sideLength`(一辺の長さ)を持つ

// `Shape` 型のオブジェクトを引数として受け取り、その面積を計算して返す関数
function getArea(shape: Shape): number {
    switch (shape.kind) {

        // 形状が円の場合の計算
        case 'circle':
            return Math.PI * shape.radius * shape.radius;
        // 形状が正方形の場合の計算
        case 'square':
            return shape.sideLength * shape.sideLength;
        // 上記のケース以外の場合
        default:
            // ここでの shape の型は `never` になります
            const _exhaustiveCheck: never = shape;
            return _exhaustiveCheck;
    }
}

上記の例では、もし将来的に Shape 型に新しい形状を追加して、それに対するケースを switch 文に追加しなかった場合、TypeScriptはエラーを報告してくれます。これは、default ケースで shape の型が never になるためです。

このように、never 型はコードが期待する動作をしているかを強化するための便利なツールとして使用されることが多いです。

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?