假设您有一个函数抛出一个专门配置的错误:
function throwMyError(): never {
throw new Error("My Custom error")
}
你有一个nullable value:
declare const str: string | null
您可以将该值缩小为不可为空的值,如下所示:
if(!str) throwMyError()
str.toLocaleLowerCase() // fine
现在把这个函数调用放在一个对象字面量中,它就不能再做同样的收缩了:
const foo = { throwMyError }
if (!str) foo.throwMyError()
str.toLocaleLowerCase() // 'obj' is possibly 'null'.(18047)
或者:
const bar = {
throwMyError: (): never => {
throw new Error()
}
}
if (!str) bar.throwMyError()
str.toLocaleLowerCase() // 'obj' is possibly 'null'.(18047)
当从对象类型调用抛出函数时,为什么范围不起作用?
是否可以在不创建类型谓词函数的情况下解决此问题?
相关问题:Type narrowing & never functions
但这似乎并没有解决这个问题,因为在所有情况下,函数类型is都显式注释为返回never