Type inference 是 TypeScript 从上下文自动推断类型,这样你就不必注释所有内容。它从初始值、return 语句和使用方式推断。
ts
let x = 10; // inferred: number
let s = "hi"; // inferred: string
const arr = [1, 2]; // inferred: number[]
const obj = { a: 1, b: };
Type inference 是 TypeScript 从上下文自动推断类型,这样你就不必注释所有内容。它从初始值、return 语句和使用方式推断。
let x = 10; // inferred: number
let s = "hi"; // inferred: string
const arr = [1, 2]; // inferred: number[]
const obj = { a: 1, b: };
function double(n: number) { return n * 2; } // return inferred as number
[1, 2, 3].map(n => n * 2); // `n` inferred as number from the array — no annotation needed
这种 contextual typing 就是为什么回调很少需要参数注释的原因 — TypeScript 知道 number[] 上的 map 传入的是 number。
let a = "hello"; // widened to string (let can be reassigned)
const b = "hello"; // narrowed to the literal type "hello"
const 推断 literal 类型,因为它永远不能改变;let 扩展到一般类型。这对 unions 很重要:
const dir = "up"; // type "up"
let dir2 = "up"; // type string
string 而不是 literal)。const xs = [] 推断为 any[] — 注释为 number[]。Inference 让 TypeScript 代码几乎和 JavaScript 一样简洁,同时保持完全的类型安全。
理解它 何时 开始工作(以及何时扩展)可以让你只在真正有帮助的地方进行注释。