Skip to content

类型 Widening

一句话解释

类型 widening occurs 当 TypeScript generalizes literal 类型 (如 5) 到它的基础类型 (如数字) 期间类型 inference, 典型地 for 可变变量.

用大白话说

类型 widening happens 当 TypeScript takes 特定 literal 类型 and 制作它 更多通用. For let x = 5, x 是 widened 到 number 相反的 staying as literal 5, because let variables can be reassigned to any number.

For const x = 5, x stays as the literal type 5 because const cannot be reassigned. You can prevent widening with as const: let x = 5 as const gives x the type 5.

Widening affects arrays too: [1, 2, 3] is inferred as 数字[], not [1, 2, 3]. Use as const to get the tuple type readonly [1, 2, 3]. Understanding widening is important for exhaustiveness checking and literal type usage.

示例

typescript
let x = 5;       // type: number (widened)
const y = 5;     // type: 5 (literal)
let arr = [1, 2]; // type: number[] (widened)
const tuple = [1, 2] as const; // type: readonly [1, 2]

let widens literal 类型; const preserves 它们. 'as const' forces literal 类型.

相关术语

解读错误信息

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

查看错误

← 返回术语表