Union 类型
一句话解释
union 类型 (| B) represents 值那个能 是要么类型 or 类型 B. pipe symbol | 读取 as 'or'.
用大白话说
union 类型 lets 值是 one 的几个类型. 你编写它 使用 pipe symbol: string | number means the value is either a string or a number. This is one of TypeScript's most powerful features.
Unions are useful for function parameters that accept multiple types, for representing results that can be different shapes (like a success or error response), and for defining a set of allowed string values (string literal unions).
When you have a value of a union type, TypeScript only lets you access properties that exist on ALL types in the union. To access type-specific properties, you need to narrow the type using type guards (typeof, instanceof, or user-defined guards).
示例
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase(); // narrowed to string
}
return value.toFixed(2); // narrowed to number
}
format("hello"); // "HELLO"
format(3.14159); // "3.14"参数能 是字符串 or 数字. typeof narrows 类型 in 每个分支.
常见混淆
容易混淆的对象: intersection 类型
关键区别: Union (| B) 平均值 '要么 or B'. Intersection (& B) 平均值 '两者都 and B simultaneously'.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。