never 的使用场景
never
类型表示永远不会存在的值或不可达的代码
用于表示永远不会返回的函数
如果一个函数永远不会正常结束(例如,它抛出异常或进入无限循环),则可以将其返回类型声明为 never
。
1
2
3
4
5
6
7
typescript复制代码function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}
这里 never
表示这些函数不会返回值,因为它们不会执行到结束。
用于类型约束
never
也可以用在一些高级类型操作中,用于创建更加严格的类型约束。
示例 1:类型不可能的情况
1
type Impossible = string & number; // 永远不可能同时是 string 和 number
这里 Impossible
类型的值永远不存在,实际等价于 never
。
示例 2:用作空联合
1
2
type EmptyUnion = never | string; // 等价于 string
type IntersectionWithNever = string & never; // 等价于 never
用于类型收窄
在联合类型中,通过类型收窄(type narrowing)来确保代码处理了所有可能的情况。如果某些分支理论上不可达,可以用 never
表示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
type Animal = Dog | Cat;
interface Dog {
kind: 'dog';
bark(): void;
}
interface Cat {
kind: 'cat';
meow(): void;
}
function handleAnimal(animal: Animal) {
switch (animal.kind) {
case 'dog':
animal.bark();
break;
case 'cat':
animal.meow();
break;
default:
assertNever(animal); // 确保处理了所有可能的情况
}
}