组合类型
联合类型(Union Type)
定义:一个变量可以是多种类型之一。
ts
type A = { a: number };
type B = { b: string };
type Union = A | B;
const u1: Union = { a: 1 }; // ✅
const u2: Union = { b: "hello" }; // ✅
const u3: Union = { a: 1, b: "hi" }; // ✅
const u4: Union = { c: true }; // ❌值可以是
A或B,也可以是两者都有。访问属性时需要类型收窄(type narrowing):
tsfunction printValue(u: Union) { if ('a' in u) { console.log(u.a); // ✅ } else { console.log(u.b); // ✅ } }
类型保护:
访问联合类型的特定属性时,需要做类型判断(Type Narrowing):
ts
function format(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}交叉类型(Intersection Type)
定义:将两个类型进行并集操作
ts
type A = { a: number };
type B = { b: string };
type Intersection = A & B;
const i1: Intersection = { a: 1, b: "hello" }; // ✅
const i2: Intersection = { a: 1 }; // ❌ 缺少 b
const i3: Intersection = { b: "hi" }; // ❌ 缺少 a- 值必须同时满足所有类型(并集就可以满足)。
- 常用于补充某个类型
示例1
ts
type A=7
type B=number
type C= A&B //7示例2
ts
type A=string
type B=number
type C=A&B //never并集为空示例3
ts
type A=7
type B=8
type C=A&B //由于 7 和 8 是互斥的字面量类型,没有任何值既能是 7 又能是 8,所以交叉结果就是 never。类型断言
告诉 TypeScript “我比编译器更清楚这个值的类型”,相当于手动覆盖推断类型。
ts
let value: unknown = "hello";
// ✅ 类型断言方式 1
let len1: number = (value as string).length;
// ✅ 类型断言方式 2(JSX 里只能用这种)
let len2: number = (<string>value).length;