function foo(item: string | null) {
if (!item) return null
return () => {
function regular() {
return item
}
const arrow = () => item
console.log(regular().toLowerCase()) // Error: Object is possibly 'null'.
console.log(arrow().toLowerCase()) // Pass
}
}
在函数foo
中,我编写了两个嵌套函数.一个是正则函数,另一个是箭头函数.虽然我认为返回的两个值的类型都应该缩小到string
,但事实是regular()
得到了string | null
类型.
起初,我认为这可能是因为函数参数item
是可变的.(在本issue中提到),所以我手动将其转换为const,但它仍然存在相同的问题:
function foo(item: string | null) {
const itemCopy = item // Make sure TypeScript know it is immutable
if (!itemCopy) return null
return () => {
function regular() {
return itemCopy
}
const arrow = () => itemCopy
console.log(regular().toLowerCase()) // Error: Object is possibly 'null'.
console.log(arrow().toLowerCase()) // Pass
}
}
还提到,它似乎与箭头功能无关.将箭头函数更改为正则函数表达式也将显示相同的行为.
function foo(item: string | null) {
if (!item) return null
return () => {
function regular() {
return item
}
const exp = function () { // Now the only difference is one is function expression while the other is not.
return item
}
console.log(regular().toLowerCase()) // Error: Object is possibly 'null'.
console.log(exp().toLowerCase()) // Pass
}
}
为什么会这样呢?这种行为是有意为之的吗?