类型 Inference in TypeScript
如何 TypeScript infers 类型 automatically and 规则 governing inference 上下文.
你将学到
- 如何 TypeScript infers 类型从 变量 initializers
- difference 之间 let and const inference (widening 对比 literal)
- Contextual 输入 for 函数参数 and 返回值
- Best 常见类型 inference for 数组 and unions
概念讲解
Automatic Inference
TypeScript infers types when you do not annotate them. let 数量 = 0 infers 数字, let name = "Alice" infers 字符串, and let 项 = [1, 2, 3] infers 数字[]. Inference follows the initializer's type, so you rarely need to annotate local variables. The golden rule is: annotate function signatures (parameters have no inference context) and public APIs, but let inference handle local variables.
let vs const and Widening
let x = "hello" infers string (the widened type), because let variables can be reassigned to any string. const x = "hello" infers the literal type "hello", because const cannot be reassigned. This distinction matters for union types and literal types. You can force widening with an explicit annotation (const x: string = "hello") or force a literal with as const (let x = "hello" as const).
Contextual Typing
TypeScript infers types from context, not just initializers. When you write ["", "b"].映射(s => s.长度), TypeScript knows s is 字符串 because 映射 is called on a 字符串[]. This contextual typing flows from the expected type into expressions, so you rarely need to annotate callback parameters. It also works with object literals, function returns, and generic type arguments — the compiler uses the surrounding context to fill in missing types.
示例代码
// let widens to the general type; const keeps the literal.
let count = 42; // inferred: number (widened)
const limit = 42; // inferred: 42 (literal type)
let name = "Alice"; // inferred: string (widened)
const greeting = "Hi"; // inferred: "Hi" (literal type)
// 'as const' forces literal types for arrays and objects.
const config = { port: 3000, host: "localhost" } as const;
// type: { readonly port: 3000; readonly host: "localhost" }
// Contextual typing — s is inferred as string from the array.
const lengths = ["apple", "banana", "cherry"].map(s => s.length);
// lengths is inferred as number[]
// Best common type — TypeScript finds the common supertype.
const mixed = [1, 2, "three"]; // inferred: (string | number)[]
// Function return type is inferred from the body.
function double(x: number) {
return x * 2; // return type inferred as number
}
console.log(count, limit, name, greeting, config.port, lengths, mixed);
TypeScript infers 类型从 initializers and 上下文. let widens 到通用类型; const keeps literals. as const forces literal/readonly 类型. Contextual 输入 infers 回调参数类型从 它们的 usage.
动手试一试
- JSON 到 TypeScript
Generated 类型 show 哪里 inference 会工作对比哪里 annotations help.
- Code Diff
Compare explicitly annotated code 使用它的 inferred equivalent.
常见错误
错误写法
Annotating 每个变量相反的 relying on inference
正确做法
Let TypeScript infer 类型 for 局部变量. 仅 annotate 函数参数, 返回类型 on 公共 APIs, and 位置哪里 inferred 类型是 也 broad or unclear.
错误写法
Expecting let 到 preserve literal 类型如 const 做
正确做法
let widens 到通用类型 (字符串, 数字) 因为变量能 是 reassigned. Use const for literal 类型, or use 'as const' 到 force 它们 on let or 对象属性.
练习 类型 Inference in TypeScript
7 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。