typeScript typeof 操作符
js 表达式中的 typeof 用来返回一个变量的基本数据类型
如 string、number、function、object
1 | typeof 1; // number |
在 ts 中,typeof 可以获取变量的声明类型
typeof在ts中用来返回一个变量的声明类型,如果不存在,则获取该类型的推论类型typeof在上下文的作用决定了返回值是类型查询/还是表达式。前者返回的是类型(types)
后者返回 变量的类型值(values)
列如在 console.log()、if判断、变量声明 let / const 等操作中 typeof 返回 变量 的 类型 的 字符串名称
而在 typeof 的限制下,typeof 返回变量的类型
1 | const n: number = 1; |
这里有一点需要说明,不能单纯的通过关键字,判断 typeof 在上下文中的作用,而是综合的来判断是属于表达式还是类型查询。比如下面的例子中,虽然出现了 let 关键字,但是很明显 typeof 出现在类型声明的位置上,因此这里是类型查询。
1 | let s: string = 'hello'; |
typeof s 返回 s 的声明类型 string
typeof 操作符用于获取变量的类型。因此这个操作符的后面接的始终是一个变量,且需要运用到类型定义当中
1
2
3 // type TD = typeof 's' // 错误 应为标识符。ts(1003)
let asoul = 's';
type AST = typeof asoul; // 正确 type AST = string
如果 typeof 接收的变量是对象,则 typeo 返回的类型不是 object,而是同样结构的类型字面量
1 | let obj = { |
如果变量没有声明类型,typeof 返回变量的推断类型
1 | let hello = 'hello world'; // ts 会自动推断为 string 类型 (let hello: string) |
tips: 什么是字面量类型?
1 | let box1: string; // box1 变量是 string 类型的,可以赋值任何字符串 |
如果定义一个变量 box2 并指定它的字面量类型为 '123'
那么它只能赋值 '123' ,其他类型一定报错,'456' 都不行
1 | let box2: '123'; // let box2: "123" |
换个角度,const 声明的 变量 是不可更改的,所以 ts 会自动把该变量推断成 字面量类型
1 | const box3 = '456'; // 此时 box3 的类型为字面量 '456',无法为 box3 重新分配变量。 const box3: "456" |
有时候,我们希望变量是常量,不允许重新分配,可使用 const 来定义变量,此时,ts 基于类型推断, 返回的类型是字面量类型(注意:字面量类型不等于字符串),如下:
1 | const world = 'the world is big'; // 返回的是字面量 const world: "the world is big" |
ts 3.4 引入了一种新的字面量构造方式,const 断言。在 const 断言的作用下,即使是 let 声明也可以限制类型扩展,变量不能重新分配,typeof 返回变量s5 字面量类型 'hi'
1 | let s5 = 'hi' as const; |
因为,当我们使用 const 断言构造新的字面量表达式时,向编程语言发出以下信号:
表达式中的任何字面量类型都不应该被扩展
对象字面量的属性,将使用 readonly 修饰
数组字面量将变成 readonly 元组
1 | let x = 'hello' as const; |
如果变量声明了 类型 ,推断不受 const 的影响,唯一不同的是:typeof 返回 s6 的声明类型 string,而不是字面量类型 'hello',但是变量依然不能重新分配
1 | const s6: string = 'hello'; |
boolean 类型是个特殊的存在,typeof 作用下将被收窄(现在还没搞懂这个收窄啥意思,有知道的评论可以教教我吗)
无论有无类型都将返回字面量 true/false
1 | let b = true; // 推断 b:boolean |