下面的示例说明了以下事实:打字稿使用双重否定(someVal
)将其转换为布尔值时可以推断出!!
不为null,但使用布尔值构造函数(更明确地)将其转换为布尔值时,则不能推断出。我个人更喜欢使用布尔构造函数来转换值,但是遇到了这个问题。有人可以告诉我为什么会这样吗?
const someVal: number | null = null
if (!!someVal) {
const res = someVal + 2; // ok
}
if (Boolean(someVal)) {
const res = someVal + 2; // Object is possibly 'null'.
}
Boolean
成为类型防护,但它尚未实现(或更准确地说,它已实现并引起了其他问题,因此将其还原)]]如果您对本期中列出的休息时间没问题,可以自己添加:
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
}