返回
创建于
状态
公开

TypeScript 中的 never

never 在 TS 中表示的是永远不会出现或者不存在的值。

一个简单的例子, 一个永远不会有返回值的函数:

text
1function foo(): never {
2  throw new Error('error')
3}
4
5function infiniteLoop(): never {
6    while (true) {
7    }
8}

有什么实际的使用场景呢?

比如我们可以用 never 排除一些我们不想要的值。

text
1type NonNullable<T> = T extends null | undefined ? never : T
2type FOO = NonNullable<number | null> // number

或者用于避免 switch case 或 if else 中会遗漏一些条件

text
1type Foo = 'a' | 'b'
2function fn(x: Foo) {
3  switch(x){
4    case 'a':
5      // ...
6    case 'b':
7      // ...
8}
9// 如果有一天将 Foo 的类型改为了 type Foo = 'a' | 'b' | 'c'
10// 上面的代码并不会报错,但却遗漏了对 'c' 的处理
11// 改为下方代码
12type Foo = 'a' | 'b'
13function fn(x: Foo) {
14  switch(x){
15    case 'a':
16      // ...
17    case 'b':
18      // ...
19    default:
20      // 如果我们将 Foo 改为 'a' | 'b' | 'c'
21      // 这里就会有 Type 'string' is not assignable to type 'never' 的报错
22      // 从而避免遗漏条件
23      const _exhaustiveCheck: never = x;
24      return _exhaustiveCheck;
25}

https://www.typescriptlang.org/docs/handbook/2/functions.html#never

https://stackoverflow.com/questions/42291811/use-of-never-keyword-in-typescript

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type