Skip to content

类型 Inference

一句话解释

类型 inference 是 TypeScript's ability 到 automatically figure out 类型的 变量 or 表达式从 它的 usage, 不使用需要 explicit annotation.

用大白话说

类型 inference 平均值 TypeScript guesses 类型 for 你. 当你 编写 let x = 5, TypeScript infers 那个 x 是数字 — 你 don't 需要到 编写 let x: number = 5. This keeps code concise while maintaining type safety.

Inference works for variables, return types, and generic type parameters. For example, if you call identity(42) where identity is <T>(x: T) => T, TypeScript infers that T is number.

There are limits: TypeScript cannot infer function parameter types (you must annotate them), and inference may widen literal types. For let x = 5, x is inferred as number (widened), but for const x = 5, x is inferred as the literal type 5.

示例

typescript
let count = 5;        // inferred: number
const pi = 3.14;     // inferred: 3.14 (literal)
let names = ["a"];  // inferred: string[]

function double(x) { return x * 2; } // Error: parameter needs annotation

TypeScript infers 类型从 initializers. 函数参数必须是 annotated explicitly.

常见混淆

  • 容易混淆的对象: 类型 annotation

    关键区别: Inference 是 automatic; annotation 是 explicit. Inference keeps code shorter, 但 annotations 是 clearer for 公共 APIs.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表