1、安装类型定义包 (只在开发和测试阶段被使用,而在生产环境中不会被包含)
npm i @types/node --save-dev
2、安装 TypeScript 执行器 -- 允许你直接运行 TypeScript 文件
npm i ts-node --g
二、any类型 -- top type
let anyType: any = 1;
anyType = "string";
anyType = true;
anyType = [1, 2, 3];
anyType = { name: "2any" };
anyType = () => { };
anyType = null;
anyType = undefined;
anyType = Symbol("2any");
anyType = {};
anyType = () => { };
anyType = 123;
2.声明变量的时候没有指定任意类型默认为any
let anyType2; // 等价于 let anyType2: any;
anyType2 = 1;
anyType2 = "string";
3.弊端如果使用any 就失去了TS类型检测的作用
三、unknown类型 -- top type
1.与any类型一样,都可以接收任意类型,但是unknown类型更加安全,不能对unknown类型的变量进行任何操
let value: unknown;
value = 1;
value = "string";
value = true;
value = [1, 2, 3];
value = { name: "2any" };
// ...
2.只能赋值给unknown类型和any类型
let bbb:unknown = '123'
let aaa:any= '456'
aaa = bbb
//报错
let names:unknown = '123'
let names2:string = names
区别1:
//any可以随意赋值
let names:any = '123'
let names2:string = names
区别2:
unknown类型不能调用属性和方法,any类型可以调用属性和方法
let names: unknown = '123'
names.length // 报错
let names2: any = '123'
names2.length // 没问题
names2.toString() // 没问题