satisfies、类型谓词与品牌类型
约 355 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › TypeScript › 高级类型 › satisfies、类型谓词与品牌类型
satisfies
保留精确推导类型的同时做类型检查:
type Color = 'red' | 'green' | 'blue';
// ❌ 用 : Color 会丢失精确类型
const palette1: Record<string, Color> = {
primary: 'red',
};
// palette1.primary 类型是 Color,而非 "red"
// ✅ 用 satisfies 保留精确类型
const palette2 = {
primary: 'red',
secondary: 'blue',
} satisfies Record<string, Color>;
// palette2.primary 类型是 "red"(字面量)类型谓词 is
自定义类型守卫:
interface Fish { swim(): void; }
interface Bird { fly(): void; }
function isFish(animal: Fish | Bird): animal is Fish {
return (animal as Fish).swim !== undefined;
}
function handle(animal: Fish | Bird) {
if (isFish(animal)) {
animal.swim(); // ✅ 类型收窄为 Fish
} else {
animal.fly(); // ✅ 类型收窄为 Bird
}
}断言函数 asserts
function assertString(value: unknown): asserts value is string {
if (typeof value !== 'string') {
throw new Error('必须是字符串');
}
}
function process(value: unknown) {
assertString(value);
value.toUpperCase(); // ✅ 类型收窄为 string
}品牌类型(Branded Type)
模拟名义类型:
type Brand<T, B> = T & { __brand: B };
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
function getUser(id: UserId) { /* ... */ }
const userId = 'abc123' as UserId;
const orderId = 'xyz789' as OrderId;
getUser(userId); // ✅
// getUser(orderId); // ❌ 类型不匹配小结
| 特性 | 作用 |
|---|---|
satisfies | 保留精确类型同时做约束 |
is | 自定义类型守卫 |
asserts | 断言函数,收窄类型 |
| Branded Type | 模拟名义类型安全 |
上一节:映射类型与模板字面量 下一节:模块系统与类型导出
