TypeScript 实用技巧
常用类型工具
Partial 与 Required
interface User {
name: string;
age: number;
email: string;
}
// 所有属性变为可选
type PartialUser = Partial<User>;
// 所有属性变为必需
type RequiredUser = Required<PartialUser>;
Record 类型
type Status = 'active' | 'inactive' | 'pending';
type StatusMap = Record<Status, string>;
const statusLabels: StatusMap = {
active: '活跃',
inactive: '未活跃',
pending: '待定',
};
类型守卫
function isString(value: unknown): value is string {
return typeof value === 'string';
}