数据类型
类型分类
基本类型
基本类型(primitive type
): A primitive type is an individual type that can not be broken down further
。
TypeScript 内置的基本数据类型有:
boolean
number
string
symbol
undefined
null
void
,可将undefined
赋值给void
类型的变量never
object
,该类型的值包含对象、数组、函数等等any
,可以包含任何值unknown
当设置strictNullChecks
为true
时,会告知 TypeScript 编译器不允许将null
和undefined
赋值给变量。
- 若变量已经声明为给定类型(不包含
null
或undefined
),则不允许将变量重新赋值为null
或undefined
- 若变量未设置初始值,则不允许使用
- 不能将
null
赋值给undefined
类型的变量,或将undefined
赋值给null
类型的变量
抽象类型
抽象类型(abstract type
),An abstract type is a type that is composed of primitive types
。
Array
Tuple
,比如:let student: [ string, number, boolean ] = [ 'Ross Geller', 27, true ]
interface
联合类型
交叉类型
交叉类型,Intersection Types
,将已有的多个类型合并成一个类型,该类型拥有这些类型的所有特性。
interface Person {
firstName: string;
lastName: string;
}
interface Student {
marks: number;
}
const student: Person & Student = {
firstName: 'Wind',
lastName: 'Stone',
marks: 90
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
key 相同类型不同
交叉类型取的多个类型的并集,但是如果同一个key
在不同类型里的类型不同,则该key
为never
。
interface Person {
firstName: string;
lastName: string;
age: number;
}
interface Student {
marks: number;
age: string;
}
let student: Person & Student = {
firstName: '',
lastName: '',
marks: 0,
age: (function a() {
throw Error()
})(),
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19