TypeScript
的 Truthiness narrowing 有如下介绍:
all coerce to false, and other values get coerced to true. You can always coerce values to booleans by running them through the Boolean function, or by using the shorter double-Boolean negation. (The latter has the advantage that TypeScript infers a narrow literal boolean type true, while inferring the first as type boolean.)
// both of these result in 'true'
Boolean("hello"); // type: boolean, value: true
!!"world"; // type: true, value: true
当我键入以下代码时,类型提示却都是 boolean
:
let x = Boolean('hello')
let y = !!'hello'
这是为何?
你应该是没有开启
strictNullChecks
或strict
的配置,null严格检查没有开启时确实会显示boolean
;也就是说当你没有开启严格检查时:
换句话说你的所有类型都将变成
anyType | null | undefined
,以你的例子来说【strictNullChecks: false
】:!!"world"
转成等价于!!"world" || !!null || !!undefined
,即类型为:true | false | false
,故最终类型为boolean
https://github.com/microsoft/TypeScript/issues/10564