首先 any 类型要慎用
首先 any 类型要慎用
js 代码会自行转译类型 导致报错
任意类型可以是 Number String Boolean Object ... 等等 JS 中存在的类型
let a: any;
可以表示 数组中的元素类型
let b: any[];
也可以这样
let b: Array<any>;
下面可以看一个函数 顺带说一下 throw new Error()
const func = (value) => { let type = typeof value; if (typeof value === "number") { return `your number is ${value}` } else if (typeof value === "string") { return `your name is ${value}` } else if (typeof value === "object") { if (value instanceof Array) { return `type is Array` } else { return `type is ${type}` } } else if (typeof value === "function") { return `type is Function` } throw new Error(`Expected value is Number or String or Array or Function or Object, but got ${type}`)};const result = func(true);console.log(result);
可以看出函数的意思 每次找到对应类型都会返回出一段字符串
如果类型中找不到 则终止 js 运行 然后在终端报错