摘要:在本教程中,您将了解 TypeScript 的 any
类型以及如何在代码中正确使用它。
TypeScript any 类型的介绍
有时,您可能需要在变量中存储一个值。但是,在编写程序时您不知道它的类型。未知值可能来自第三方 API 或用户输入。
在这种情况下,您希望**跳过类型检查**并允许值通过编译时检查。
例如
let result: any;
result = 1;
console.log(result);
result = 'Hello';
console.log(result);
result = [1, 2, 3];
const total = result.reduce((a: number, b: number) => a + b, 0);
console.log(total);
Code language: JavaScript (javascript)
输出
在这个例子中
- 首先,使用
any
类型声明变量result
。 - 其次,将数字 1 赋值给
result
并将其值显示到控制台。 - 第三,将字符串字面量
'Hello'
赋值给result
并将其值显示到控制台。 - 最后,将一个数字数组赋值给
result
变量,使用reduce()
方法计算total
,并将total
记录到控制台。
让我们再看一个典型的例子
// json may come from a third-party API
const json = `{"latitude": 10.11, "longitude":12.12}`;
// parse JSON to find location
const currentLocation = JSON.parse(json);
console.log(currentLocation);
Code language: JavaScript (javascript)
输出
{ latitude: 10.11, longitude: 12.12 }
Code language: CSS (css)
在这个例子中,TypeScript 将 currentLocation
变量的值推断为 any
。我们将 JSON.parse()
函数返回的对象赋值给 currentLocation
变量。
但是,当我们访问 currentLocation
变量的非存在属性 (x
) 时,TypeScript 不会进行任何检查。
这工作正常,并在控制台中显示 undefined
值。
console.log(currentLocation.x); // undefined
Code language: JavaScript (javascript)
输出
undefined
Code language: JavaScript (javascript)
TypeScript 编译器不会报错或发出任何错误。
any
类型为您提供了一种处理现有 JavaScript 代码库的方法。它允许您在编译期间逐步选择加入和退出类型检查。因此,您可以使用 any
类型将 JavaScript 项目迁移到 TypeScript。
TypeScript any:隐式类型
如果您声明一个变量而没有指定类型,TypeScript 会假设您使用的是 any
类型。此功能称为类型推断。TypeScript 会猜测变量的类型。例如
let result;
Code language: JavaScript (javascript)
在这个例子中,TypeScript 为您推断类型。这种做法称为隐式类型。
请注意,要禁用对 any
类型的隐式类型,您需要将 tsconfig.json
文件中的 noImplicitAny
选项更改为 true。您将在后面的教程中详细了解 tsconfig.json
。
TypeScript any 与 object
如果您使用 object
类型声明一个变量,您也可以将任何值赋值给它。但是,即使方法存在,您也不能调用它。例如
let result: any;
result = 10.123;
console.log(result.toFixed());
result.willExist(); //
Code language: JavaScript (javascript)
在这个例子中,即使 willExist()
方法在编译时不存在,TypeScript 编译器也不会发出任何警告,因为 willExist()
方法可能在运行时可用。
如果运行代码,您将在控制台窗口中看到以下错误消息
TypeError: result.willExist is not a function
Code language: JavaScript (javascript)
但是,如果您将 result
变量的类型更改为 object
,TypeScript 编译器将发出两个错误
let result: object;
result = 10.123;
result.toFixed();
Code language: JavaScript (javascript)
错误
app.ts:2:1 - error TS2322: Type 'number' is not assignable to type 'object'.
2 result = 10.123;
~~~~~~
app.ts:3:8 - error TS2339: Property 'toFixed' does not exist on type 'object'.
3 result.toFixed();
~~~~~~~
Found 2 errors in the same file, starting at: app.ts:2
Code language: JavaScript (javascript)
总结
- TypeScript 的
any
类型允许您存储任何类型的值。它指示编译器跳过类型检查。 - 使用
any
类型存储在编译时不知道其类型的值,或者在将 JavaScript 项目迁移到 TypeScript 项目时。