让 TypeScript 通过推断自己判断类型,并理解为什么 unknown 胜过危险的 any。
在 Kodokon 中打开本课好消息:你不必为每一个变量都写注解。得益于类型推断,TypeScript 会根据你赋给变量的值推断出它的类型。只写 let city = "Lyon" 就足够了:TypeScript 知道 city 是一个 string,并像你手动注解过一样保护它。
let city = "Lyon"; // inferred type: string
let count = 3; // inferred type: number
count = count + 1; // accepted
// city = 42; -> error: city is still a stringany 类型的意思是“任何东西”。一个 any 变量逃过所有检查:TypeScript 接受一切,不做任何核实。这就像解开了安全带:代码能通过编译,但错误会在运行时卷土重来——而这恰恰是 TypeScript 本该防止的。
let data: any = "hello";
data = 42; // accepted without complaint
// Compiles, but crashes at runtime:
// data.toUpperCase() does not exist on a number!对于类型确实未知的值(服务器响应、用户输入),优先使用 unknown。和 any 一样,它接受任何值,但它强制你先检查类型(例如用 typeof)再使用。这样安全性依然完好无损。
let value: unknown = "hello";
// console.log(value.toUpperCase()); -> rejected!
if (typeof value === "string") {
console.log(value.toUpperCase()); // "HELLO"
}