any
TypeScript 也有一个特殊的类型,any
,当你不希望某个特定的值导致类型检查错误时,你可以使用它。
TypeScript also has a special type, any
, that you can use whenever you don't want a particular value to cause typechecking errors.
当一个值的类型为 any
时,您可以访问它的任何属性(这又将是 any
类型),像函数一样调用它,将它分配给(或从)任何类型的值,或者几乎任何其他东西这在语法上是合法的:
When a value is of type any
, you can access any properties of it (which will in turn be of type any
), call it like a function, assign it to (or from) a value of any type, or pretty much anything else that's syntactically legal:
let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking, and it is assumed
// you know the environment better than TypeScript.
obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n: number = obj;
当你不想写出一个长类型来让 TypeScript 相信特定的代码行是可以的时,any
类型很有用。
The any
type is useful when you don't want to write out a long type just to convince TypeScript that a particular line of code is okay.