ts基本数据类型
字符串
let str1: string = '123';
let str2: string = '哈哈哈';
数字
let num1: number = 123;
let num2: number = 234.56;
布尔
let bool:boolean = fale;
let bool:boolean = true;
数组
// 数组的第一种定义
let list:number[] = [1,2,3,4,5];
let list:string[] = ['1','2','3','4','5'];
let list:any[] = [1,2,4,{a:1},'23']
// 数组的第二种定义
let list:Array<number> = [1,2,3,4,5];
let list:Array<string> = ['1','2','3','4','5'];
let list:Array<any> = ['1','2',{a:1},4,5,true,flase,true];
元组(Tuple)
类似于数组(长度和类型都固定的数组),元组的特点:
- 长度固定
- 类型可以不一样
- 用于表示一个固定的结构
let tuple1:[number,number] = [100,100];
let tuple2:[string,number] = ['哈哈哈',25];
枚举(enum)
enum Sex{
Boy,
Girl
}
/* 枚举的解析
var Sex;
(function (Sex) {
Sex[Sex["Boy"] = 0] = "Boy";
Sex[Sex["Girl"] = 1] = "Girl";
})(Sex || (Sex = {}));
相当于
Sex{
'Boy': 0,
'Girl': 1,
0: 'Boy',
1: 'Girl'
}
*/
常数枚举
const enum Colors{
Red,
Yellows,
Blue
}
console.log(Colors.Red,Colors.Yellows,Colors.Blue)
// 解析后
console.log(0 /* Red */, 1 /* Yellows */, 2 /* Blue */);
Null和Undefined
/*null: 空
undefined: 未定义
它们都是其他类型的子类型,你可以把他们赋值给其他类型的变量,but得在tsconfig.json中把strictNullChecks的属性值设置为false;
*/
let name1:string | null = null;
let name2:string = undefined;
let x: number | null | undefined;
x = 1;
x = undefined;
x = null

Any(任意类型)
用于
- 数据结构太复杂太灵活的时候或者
- 类型类型转换的时候
- 第三方库没有类型定义
// 对应我们不知道的类型可以用any
let noType: any = document.getElementByClassName('.any');
let root: HTMLElement | null = document.getElementById('root');
// ts为DOM提供了一整套类型声明
// (!)强行告诉你我不会为null
root(!).style.color = '#000000'
Void(空的)
- 常用于函数有木有返回值
- void声明一个变量的时候只有两个值:undefined、null
// 常用于函数有木有返回值
function print(name:sting):void | null{
console.log(name)
// 没有return 说明函数没有返回值
// return null | undefined 这个是可以返回的
}
// void声明一个变量的时候只有两个值:undefined、null
let unusable1:void = null; //如果strictNullChecks:true的时候,会报错
let unusable2:void = undefined;

Never(永远不)
never 是其他类型子类型,代表不会出现的值
- never类型是任何类型的子类型,也可以赋值给任何类型
- 没有类型是never的子类型或可以赋值给never类型(除了never本身之外)。 即使 any也不可以赋值给never。
// never类型是任何类型的子类型,也可以赋值给任何类型
let num123: never;
// 没有类型是never的子类型或可以赋值给never类型
num123 = 123; Type '123' is not assignable to type 'never'.
// 有两种情况
// 第一种情况: 在函数内部会抛出错误,导致函数无法正常结束
function createError(message:string):never{
throw new Error(message)
// 永远不会走到这里
console.log('end')
}
// 第二种情况: 出现死循环
function sum():never{
while(true){
console.log('hello')
}
// 永远不会走到这里
console.log('end')
}