当前位置: 首页 > 知识库问答 >
问题:

typescript - 关于 TypeScript Truthiness narrowing 的一个疑问?

戚云
2024-03-31

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'

image.png

这是为何?

共有2个答案

刘升
2024-03-31

因为你使用 let 声明变量,这代表它之后可能修改为其它值,ts 只能假设它为 boolean 类型,如果你改为使用 const 声明,可以看到变量的类型为 true:

const x = Boolean('hello') // booleanconst y = !!'hello' // true

你也可以手动声明变量的类型为 true:

let y: true = !!'hello'
燕志学
2024-03-31

你应该是没有开启strictNullChecksstrict的配置,null严格检查没有开启时确实会显示boolean

默认情况下null和undefined是所有类型的子类型

也就是说当你没有开启严格检查时:

const str: 'hello' = null; // okconst bol: true = null; // ok

换句话说你的所有类型都将变成anyType | null | undefined,以你的例子来说【strictNullChecks: false】:
!!"world"转成等价于!!"world" || !!null || !!undefined,即类型为:true | false | false,故最终类型为boolean

https://github.com/microsoft/TypeScript/issues/10564

 类似资料:
  • nuxt中建api时一个文件就需要对应一个api函数吗?不能一个文件写多个api接口吗?

  • 以下代码在 chrome 输出 1,2,3 这个在网上找到了,forEach 一开始就已经获取了 数组长度 The range of elements processed by forEach is set before the first call to callbackfn. Elements which are appended to the array after the call to

  • 1.首先,我想确认一下从编程的角度,我们有“静态类型检查”和“动态类型检查,对把? 2.一般情况下我们用typescript做静态类型检查,检查源码里面自定义数据类型,对把? 3.那么,我们做的所谓的动态类型检查是不是指的那些库,比如Joi,ajv什么的,比如你点击一个按钮,然后调这个库来检查一个obj的schema,如果类面的key value类型都能对的上,我们就通过,如果类型对不上,我们就报

  • 刚开始学习java,在使用commons-dbutils操作数据库,对其进一步封装的时候,有下面两种方式: 为什么在方式2会存在Unchecked cast警告?

  • 我有一个用例,我想建立一个Kafka集群,最初我有1个Kafka Broker(A)和1个Zookeeper节点。以下是我的疑问: > 在向集群添加新的Kafka Broker(B)时。代理A上存在的所有数据都会自动分发吗?如果不是,我需要做的是分发数据。 不,让我们假设情况以某种方式解决了!我的数据分布在两个代理上。现在由于一些维护问题,我想关闭服务器B。 如何将经纪商B的数据传输到已经存在的经

  • 这段时间我在学习Spring框架。 现在我正在研究春豆的生命周期,尤其是关于豆子的日化和破坏,阅读本教程: http://www.tutorialspoint.com/spring/spring_bean_life_cycle.htm 我已经实现了前一篇文章中提出的示例,但我对这个论点有疑问。 在这个例子中,我只有两个类:HelloWorld。java和MainApp。JAVA 在地狱世界。jav