개념
Bottom type을 나타내기 위해 사용하는 것
어떠한 값도 할당할 수 없다.
Exhaustive Check (Bottom type)
function foo(x: string | number): boolan {
if (typeof x === 'string') {
return true
} else if (typeof x === 'number') {
return false
}
return fail()
}
function fail(): never {
throw new Error()
}
어떠한 값도 할당할 수 없다.
let a: never = null // Type 'null' is not assignable to type 'never'.(2322)
let b: never = undefined // Type 'undefined' is not assignable to type 'never'.(2322)
let c: never = 0 // Type 'number' is not assignable to type 'never'.(2322)
void와 혼동
void
void, never 둘다 아무것도 반환하지 않는 것이지만, void는 하나의 단위이고 never는 모순.
아무것도 반환하지 않는 함수는 void를 반환.
영원히 리턴하지 않는 함수 또는 항상 error를 던지는 함수는 never
never type 추론
never를 명시해주지 않으면 any로 추론한다. 이유는 JS와 호환성 유지
function fail(): never {
throw new Error()
}
참고
https://radlohead.gitbook.io/typescript-deep-dive/type-system/never
'IT > typescript' 카테고리의 다른 글
[Typescript] enum vs union (0) | 2024.02.05 |
---|---|
TS - 5.0 New features (0) | 2023.07.01 |
TS - unknown vs any (0) | 2023.06.27 |
TS - Extract<T, U> (0) | 2023.06.27 |
TS - Exclude<T, U> (0) | 2023.06.27 |