下面的例子说明了这样一个事实: typescript可以在使用双重否定(!!)将其转换为布尔值时推断出someVal不为空,但在使用布尔构造函数(更明确地)转换时则不能。我个人更喜欢使用布尔构造函数来转换值,但遇到了这个问题。有人能告诉我为什么会这样吗?
const someVal: number | null = null
if (!!someVal) {
const res = someVal + 2; // ok
}
if (Boolean(someVal)) {
const res = someVal + 2; // Object is possibly 'null'.
}
发布于 2019-11-14 16:13:25
有一个使Boolean成为类型保护的open issue,但它只是还没有实现(或者更准确地说,它已经实现并导致了其他问题,所以它被恢复了)
如果你对问题中概述的中断没有意见,你可以自己添加:
const someVal: number | null = null
interface BooleanConstructor {
<T>(value?: T): value is Exclude<T, false | null | undefined | '' | 0>;
}
if (Boolean(someVal)) {
const res = someVal + 2; // Ok now
}https://stackoverflow.com/questions/58851851
复制相似问题