TypeScript 特殊类型
TypeScript 有一些特殊类型,它们可能不会引用任何特定类型的数据。
类型: any
any 是一种禁用类型检查并有效地允许使用所有类型的类型。
下面的实例不使用 any,并将抛出一个错误:
不使用 any 的实例:
let u = true;u = "string"; // Error: Type 'string' is not assignable to type 'boolean'.u.runANonExistentMethod(); // Error: Property 'runANonExistentMethod' does not exist on type 'boolean'.console.log(Math.round(u)); // Error: Argument of type 'boolean' is not assignable to parameter of type 'number'.
将 any 设置为特殊类型 any 将禁用类型检查:
使用 any 的实例:
let v: any = true;v = "string"; // no error as it can be "any" type// v.runANonExistentMethod();// no type error in the editor, but will still throw an error if commented inconsole.log(Math.round(u)); // no error as it can be "any" type
any 很容易引发错误,因为它禁用了类型检查,但TypeScript 将无法提供类型安全性,并且依赖类型数据的工具(如自动完成)将无法运行,所以尽量避免使用它。类型: unknown
unknown 与 any 类似,但更安全。
TypeScript 将阻止使用 unknown 类型,如下例所示:
let w: unknown = 1;w = "string"; // no errorw = {runANonExistentMethod: () => {console.log("I think therefore I am");}} as { runANonExistentMethod: () => void }// How can we avoid the error for the code commented out below when we don't know the type?// w.runANonExistentMethod(); // Error: Object is of type 'unknown'.if(typeof w === 'object' && w !== null) {(w as { runANonExistentMethod: Function }).runANonExistentMethod();}// Although we have to cast multiple times we can do a check in the if to secure our type and have a safer casting
将上面的实例与前面的使用 any 的实例进行比较。
当您不知道要输入的数据类型时,最好使用
unknown。若要稍后添加类型,需要将其强制转换。强制转换是指我们使用 "as" 关键字表示属性或变量属于强制转换类型。类型: never
无论何时定义错误,never 都会有效地抛出错误。
let x: never = true; // Error: Type 'boolean' is not assignable to type 'never'.
never 很少使用,尤其是它本身,主要用于高级泛型。类型: undefined & null
undefined 和 null 是分别引用 undefined 和 null 的 JavaScript 原生类型。
let y: undefined = undefined;console.log(typeof y);let z: null = null;console.log(typeof z);
除非在
tsconfig.json 文件中启用 strictNullChecks,否则这些类型没有多大用处。