gpt4 book ai didi

typescript - 我怎样才能让 TypeScript 判断我的函数不可能返回?

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:38 24 4
gpt4 key购买 nike

我有这个代码:

function A(): never {
throw new Error("fail");
}

function B(): never {
A();
}

我得到这个错误:

index.ts(5,36): error TS2534: A function returning 'never' cannot have a reachable end point.

为什么会出现此错误?显然,A 永远不会返回,因此 B 没有可到达的终点。

最佳答案

这是编译器的限制。 Ryan Cavanaugh 解释 here :

The limitation here has to do with the way the compiler is designed -- control flow analysis happens before typechecking, but we would need type information (as well as identifier resolution) to determine that the fail() call points to a function that is : never

此引文上下文中的 fail() 调用与此处提出的问题中的 A() 本质上是相同的。我从上面的引述中推断,到控制流分析完成时,A() 无法返回的事实尚不清楚,因此假设隐式 return B 末尾的 undefined; 将被执行,因此 B 将返回 undefined 而不是根本不返回。修复方法如评论所在的问题报告中所述,只需在调用永不返回的函数之前添加 return 即可:

function B(): never {
return A();
}

关于typescript - 我怎样才能让 TypeScript 判断我的函数不可能返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41002864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com