详细版简单易学版TypeScript各类型声明
假如本地新建了一个b.ts文件

安装TypeScript:npm install -g typescript
编译代码:tsc b.ts
运行js:node b.js
在终端输入 tsc -init 生成 tsconfig.json 文件
类型注解:TypeScript里的类型注解是一种轻量级的为函数或变量添加约束的方式
ts编译器:TypeScript提供了静态的代码分析,它可以分析代码结构和提供的类型注解
根据官方 TypeScript 的注意事项,建议不要使用 Number、String、Boolean、Symbol 或 Object。
ts各类型声明的代码如下:
一、字符串类型
let str: string = 'hello';
str = 'ts';
二、数字类型
let num: number = 123;
num = 456;
三、布尔类型
let flag: boolean = true;
flag = false;
四、undefined和null
// tsconfig.json 的 "strict": false 时,可以把undefined和null赋值给其他类型的变量
// tsconfig.json 的 "strict": true 时, 🙅不可以把undefined和null赋值给其他类型的变量
let str1: string = undefined;
let num1: number = null;
tsconfig.json 的 "strict": true 时,查看报错:
1、

2、

五、数组
// 1、空数组:可以不规定数组元素的类型
let arr1: [] = [];
// 2、非空数组:需要规定数组元素的类型
// 定义数组方式一:普通写法 元素类型[]
let arr2: number[] = [];
let arr3: number[] = [1, 2, 3];
// 定义数组方式二:范型写法 Array<元素类型>
let arr4: Array<number> = [];
let arr5: Array<number> = [4, 5, 6];
六、对象
let obj: object = {};
// 不能将 number、string、boolean 赋值给对象
obj = 123; // 报错
obj = 'str'; // 报错
obj = true; // 报错
// tsconfig.json 的 "strict": false 时,可以把undefined和null赋值给obj
// tsconfig.json 的 "strict": true 时, 🙅不可以把undefined和null赋值给obj
obj = null;
obj = undefined;
obj = [];
obj = new String();
obj = String;
假如将 number、string、boolean 赋值给对象,查看报错:
1、

2、

3、

七、any:任何类型
// 如果我们🤷不知道声明的变量要接受什么类型的值,可以用any,帮助代码通过编译阶段
let test: any = 123;
// 优点:任何类型的值都可以赋给test
test = "str";
test = null;
test = [];
// ......
// 缺点:arr6的每个元素设置成了any后,ts编译器不会对每个元素做类型检查,当js运行代码时第10行代码就会报错
let arr6: any[] = [1, 2, 3, "str", false];
console.log(arr6[0].split(' ')); // js运行时会报错,因为数字1没有split()方法
js运行时报错,查看报错:

八、void:空值
// void表示没有任何类型、没有任何返回值
// 通常用于函数,void表示该函数没有返回值,调用该函数会得到undefined,相当于在函数内部 return undefined
function func(): void {
console.log("这是void");
}
console.log(func()); // undefined
// void只能给undefined定义类型,因为void就是表示没有任何类型
let un1: void = undefined;
// 👆上面那样写没什么意义,因为undefined本身就是一个类型,等价于👇下面这样写
let un2: undefined = undefined;