TypeScript never型
never型は、関数が戻り値を返さず、かつ呼び出し元に制御を戻すことが決してない状況を表すための特殊な型。
これは、関数が例外を投げるか、終了しない無限ループに入る場合など、正常終了しないことを示す時に使用される。
void型が何も関数を返さないのに対し、never型は関数が正常に戻る「終了点」を持たないことを意味する。
ts
function throwError(message: string): never {
throw new Error(message)
}
function infiniteLoop(): never {
while (true) {
console.log('infinite loop')
}
}
type Shape = 'circle' | 'square' | 'triangle'
function handleShapes(shape: Shape) {
switch (shape) {
case 'circle':
console.log('circle')
break
case 'square':
console.log('square')
break
case 'triangle':
console.log('triangle')
break
default: {
const exhaustiveCheck: never = shape
throw new Error(`Unhandled shape type: ${exhaustiveCheck}`)
}
}
}
handleShapes('circle')
// handleShapes('hexagon')
// 型 '"hexagon"' の引数を型 'Shape' のパラメーターに割り当てることはできません。