通常,TypeScript 可以借助防护和返回来推断变量的类型:
type Pet = Dog | Cat;
function isDog(pet: Pet): pet is Dog {
return true;
}
function fn1(pet: Pet) {
if (isDog(pet)) {
return;
}
// At this point, TS knows that `pet` is a `Cat`.
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将 return 更改为process.exit,这将不再起作用:
function fn2(pet: Pet) {
if (isDog(pet)) {
process.exit(1);
}
// At this point, we know that `pet` should be a `Cat`, but TS doesn't know.
}
Run Code Online (Sandbox Code Playgroud)
process.exit有没有办法让我以类似的方式向编译器发出信号,表明程序将在之后结束return?
当然,我可以在 后面添加一个 return process.exit。然而,在我的实际代码中,我的函数正在返回一些东西,调用它,这样当is aMyObject时没有合理的值,因此强制退出。petDog
我知道我可以做一些类型断言来解决这个问题,但想知道什么是解决这个问题的好方法。
我相信这是 Typescript(即使是最新版本)的限制。
解决方法:
你可以return process.exit(1)。
type Pet = Dog | Cat
function isDog(pet: Pet): pet is Dog {
return true
}
function fn1(pet: Pet) {
if (isDog(pet)) {
return process.exit(1)
}
return console.log(pet)
}
Run Code Online (Sandbox Code Playgroud)
Typescript 推断pet是一个Cat.
小智 3
这是 TypeScript 的设计限制,并且无意修复它。它不会知道这process.exit()会导致进程退出,就像您使用一个总是抛出异常的函数一样,它也不会知道这一点。即使你的函数返回never.
维护者引用:
您的示例中的可达性由类型决定,但图表是根据语法构建的。
作为更好的解决方法,您可以编写:
return process.exit(0);
Run Code Online (Sandbox Code Playgroud)
类似问题:https://github.com/microsoft/TypeScript/issues/8655
| 归档时间: |
|
| 查看次数: |
13702 次 |
| 最近记录: |