TypeScript 高级类型 — 联合与交叉
联合类型、交叉类型、类型别名、字面量类型 · 难度:高级 · +15XP
联合类型(Union)
表示"或"的关系——一个值可以是多种类型之一:
type Status = "active" | "inactive" | "banned";
let userStatus: Status = "active"; // ✅
// userStatus = "deleted"; // ❌ 不在范围内
function printId(id: number | string) {
if (typeof id === "string") console.log(id.toUpperCase());
else console.log(id);
}
交叉类型(Intersection)
表示"且"的关系——合并多个类型的属性:
interface Name { name: string; }
interface Age { age: number; }
type Person = Name & Age; // { name: string; age: number }
字面量类型
// 不仅是类型,还能精确到具体的值
type Direction = "up" | "down" | "left" | "right";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
function request(url: string, method: HttpMethod) { ... }