英文:
Why doesn't typescript narrow types with control flow and never when using arrow functions
问题
Typescript 拒绝使用 fail
调用来缩小类型,但会接受使用 fail2
调用来缩小类型。这是 TypeScript 中的一个 bug 吗?
这里 是一个演示环境,如果你想尝试切换注释并查看错误是否消失。
为了更清晰,以下是一些屏幕截图
有错误时
没有错误时
英文:
Typescript refuses to narrow with a call to fail
but will narrow with a call to fail2
. Is this a bug in typescript?
const fail = (message?: string): never => {
throw new Error(message);
};
function fail2(message?: string): never {
throw new Error(message);
}
const getData = (): string | null => {
return "the-data";
}
export const loadDataOrError = (): string => {
const data = getData();
if (data === null) {
// Swap the below and see that it works
// fail2();
fail();
}
// This errors
return data;
};
here is a playground if you want to try switching the comments and seeing the error vanish.
Screenshots for clarity
With an error
Without an error
答案1
得分: 5
根据这个在GitHub上开放的问题,这是TypeScript中类型缩小目前如何工作的一个限制。如果你想要解决这个问题,你可以像这样明确注释箭头函数类型:
const fail: (message?: string) => never = (message) => {
throw new Error(message)
}
英文:
According to this open GitHub issue this is a limitation of how type narrowing currently works in typescript. If you want to remedy it you can explicitly annotate arrow function types like so:
const fail: (message?: string) => never = (message) => {
throw new Error(message)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论