关于 TypeScript Truthiness narrowing 的一个疑问?-灵析社区

正确计算方式

`TypeScript` 的 [Truthiness narrowing](https://link.segmentfault.com/?enc=09uZPoBPhTJVy3EXR1NvGA%3D%3D.%2Fj4CIx96AnfgXHI22yCp1N79j3nmrSEUOtRlHXgSAFtC7UQlPoEUloXqOJm1t7sNCnPbEIWC6nY6YLLsLpXv19wj5QR5BHPIp04P8kYGxTjBqLXgI6olRiyNbRuCSsL4) 有如下介绍: > 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' ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241004/bfed2d37487f71426e9d5121b9da0015.png) 这是为何?

阅读量:201

点赞量:0

问AI
你应该是没有开启"strictNullChecks"或"strict"的配置,null严格检查没有开启时确实会显示"boolean"; «默认情况下null和undefined是所有类型的子类型» 也就是说当你没有开启严格检查时: const str: 'hello' = null; // ok const bol: true = null; // ok 换句话说你的所有类型都将变成"anyType | null | undefined",以你的例子来说【"strictNullChecks: false"】: "!!"world""转成等价于"!!"world" || !!null || !!undefined",即类型为:"true | false | false",故最终类型为"boolean" "https://github.com/microsoft/TypeScript/issues/10564" (https://link.segmentfault.com/?enc=IqWPkw3770YiHGGVzYoU3w%3D%3D.sGTTGr7qiqUfp8DiDdZ5fUNwuu6im9Yqna%2Fd387lqyBTxpYI0IqPtIgGjBo%2BtZWlz%2F85CBstzIjvUtgWhIx%2FcQ%3D%3D)