数据类型
基本类型
布尔值
typescript
const isTrue:boolean = true
const gender:boolean = false
1
2
2
数值
typescript
const age:number = 15
const num:number = 22
const num1:number = NaN
const num2:number = Infinity // 无限
1
2
3
4
2
3
4
字符串
typescript
const name1:string = 'tom'
const name2:string = `${name1} and jerry`
1
2
2
null、undefined
undefined
和 null
是两种独立类型,它们各自都只有一个值。
typescript
let udF: undefined = undefined
let n: null = null
1
2
3
2
3
注意
注意,如果没有声明类型的变量,被赋值为undefined
或null
,在关闭编译设置noImplicitAny
和strictNullChecks
时,它们的类型会被推断为any
。
typescript
// 关闭 noImplicitAny 和 strictNullChecks
let ud = undefined; // 类型推断为 any
let ay = null // 类型推断为 any
1
2
3
4
2
3
4
如果希望避免这种情况,则需要打开编译选项strictNullChecks
。
typescript
// 打开编译设置 strictNullChecks
let ud = undefined; // 类型推断为 undefined
let ay = null // 类型推断为 null
1
2
3
4
2
3
4
上面示例中,打开编译设置strictNullChecks
以后,赋值为undefined
的变量会被推断为undefined
类型,赋值为null
的变量会被推断为null
类型。
symbol
typescript
const s:symbol = Symbol(20)
1
bigint
新出的类型,但是请注意
- 目标低于 ES2020 时,BigInt 字面量不可用。
- 需要在
tsconfig.json
中,配置target
为ES2020
或以上
javascript
const bi:bigint = 1n
1
任意类型
any
any
类型表示没有任何限制,该类型的变量可以赋予任意类型的值。也可以被赋值为任意类型的值。
typescript
let x: any;
x = 1
x = true
x = 'string
1
2
3
4
5
2
3
4
5
类型污染
变量类型一旦设为any
,TypeScript
实际上会关闭这个变量的类型检查。即使有明显的类型错误,只要句法正确,都不会报错。
typescript
// 这样造成了类型污染
let x: any;
let m: number = 1;
m = x;
1
2
3
4
5
2
3
4
5
unknown
表示类型不确定,可能是任意类型,但是它的使用有一些限制,不像any
那样自由,可以视为严格版的any
。
unknown
跟any
的相似之处,在于所有类型的值都可以分配给unknown
类型
typescript
let x: unknown;
x = 1
x = 'string'
x = true
1
2
3
4
5
2
3
4
5
无法造成类型污染
typescript
let x: unknown;
let m: number = 1;
m = x // 报错:Type 'unknown' is not assignable to type 'number'.
1
2
3
2
3
提示
unknown
类型变量能够进行的运算是有限的,只能进行比较运算(运算符==
、===
、!=
、!==
、||
、&&
、?
)、取反运算(运算符!
)、typeof
运算符和instanceof
运算符这几种,其他运算都会报错。