# 2.基础类型
TS中冒号后面的都为类型标识
# 一.布尔、数字、字符串类型
let bool:boolean = true;let num:number = 10;let str:string = 'hello zf';
1
# 二.元组类型
限制长度个数、类型一一对应
let tuple:[string,number,boolean] = ['zf',10,true];// 像元组中增加数据,只能增加元组中存放的类型tuple.push('回龙观');
1
# 三.数组
声明数组中元素数据类型
let arr1: number[] = [1, 2, 3];
let arr2: string[] = ['1', '2', '3'];
let arr3: (number | string)[] = [1, '2', 3];
let arr4: Array<number | string> = [1, '2', 3]; // 泛型方式来声明
1
2
3
4
5
2
3
4
5
# 四.枚举类型
enum USER_ROLE {
USER, // 默认从0开始
ADMIN,
MANAGER
}// {0: "USER", 1: "ADMIN", 2: "MANAGER", USER: 0, ADMIN: 1, MANAGER: 2}
1
2
3
4
5
6
2
3
4
5
6
可以枚举,也可以反举
(function (USER_ROLE) {
USER_ROLE[USER_ROLE["USER"] = 0] = "USER";
USER_ROLE[USER_ROLE["ADMIN"] = 1] = "ADMIN";
USER_ROLE[USER_ROLE["MANAGER"] = 2] = "MANAGER";
})(USER_ROLE || (USER_ROLE = {}));
1
2
3
4
5
6
2
3
4
5
6
异构枚举
enum USER_ROLE { USER = 'user', ADMIN = 1, MANAGER,}
1常量枚举
const enum USER_ROLE { USER, ADMIN, MANAGER,} console.log(USER_ROLE.USER)// console.log(0 /* USER */);
1
2
# 五.any类型
不进行类型检测
let arr:any = ['jiagou',true,{name:'zf'}]
1
# 六.null 和 undefined
任何类型的子类型,如果strictNullChecks
的值为true,则不能把null 和 undefined付给其他类型
let name:number | boolean;name = null;
1
# 七.void类型
只能接受null,undefined。一般用于函数的返回值
let a:void;a = undefined;
1
严格模式下不能将null赋予给void
# 八.never类型
任何类型的子类型,never代表不会出现的值。不能把其他类型赋值给never
function error(message: string): never {
throw new Error("err");
}
function loop(): never {
while (true) { }
}
function fn(x: number | string) {
if (typeof x == 'number') {
} else if (typeof x === 'string') {
} else {
console.log(x); // never
}
}
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
# 九.Symbol类型
Symbol表示独一无二
const s1 = Symbol('key');
const s2 = Symbol('key');
console.log(s1 == s2); // false
1
2
3
4
2
3
4
# 十.BigInt
类型
const num1 = Number.MAX_SAFE_INTEGER + 1;
const num2 = Number.MAX_SAFE_INTEGER + 2;
console.log(num1 == num2); // true
let max: bigint = BigInt(Number.MAX_SAFE_INTEGER);
console.log(max + BigInt(1) === max + BigInt(2));
1
2
3
4
5
6
2
3
4
5
6
number类型和bigInt类型是不兼容的
# 十一.object对象类型
object
表示非原始类型