Discriminated Union
一句话解释
discriminated union 是 union 的对象类型那个 share 常见属性 (discriminant), 启用类型 narrowing 通过切换语句.
用大白话说
A discriminated union is a pattern where multiple object types share a common property with different literal values. This property (the discriminant) lets TypeScript narrow the type in switch statements.
例如, 类型 Shape = { kind: "circle"; r: 数字 } | { kind: "square"; s: 数字 }. The kind property is the discriminant. In 切换 (shape.kind), TypeScript narrows shape to the correct type in each case.
Discriminated unions are the idiomatic way to model variant data in TypeScript — different shapes of data with a common tag. They are used for state machines, AST nodes, API responses, and Redux actions.
示例
type Result =
| { ok: true; value: number }
| { ok: false; error: string };
function handle(r: Result) {
switch (r.ok) {
case true: return r.value; // narrowed to success
case false: return r.error; // narrowed to failure
}
}'好的' 属性是 discriminant. 切换 narrows 类型 in 每个情况.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。