
高级 TypeScript 模式
TypeScript 提供了强大的类型系统,掌握高级模式可以显著提高代码质量。
1. 泛型模式
工具函数
function identity<T>(arg: T): T {
return arg;
}// 使用示例
const output = identity<string>('hello');
泛型约束
interface Lengthwise {
length: number;
}function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
2. 条件类型
type ExtractType<T> = T extends string ? 'string' :
T extends number ? 'number' :
T extends boolean ? 'boolean' : 'unknown';type Test = ExtractType<string>; // 'string'
3. 映射类型
type Optional<T> = {
[P in keyof T]?: T[P];
};interface User {
name: string;
age: number;
}
type OptionalUser = Optional<User>;
// 等同于 { name?: string; age?: number; }
4. 实用工具类型
// Partial - 使所有属性可选
type PartialUser = Partial<User>;// Pick - 选择特定属性
type UserPreview = Pick<User, 'name'>;
// Omit - 排除特定属性
type UserWithoutAge = Omit<User, 'age'>;
// Record - 创建对象类型
type UserRoles = Record<string, 'admin' | 'user'>;
5. 装饰器
function logged(originalMethod: any, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
function replacementMethod(this: any, ...args: any[]) {
console.log(LOG: Entering method ${methodName}.);
const result = originalMethod.call(this, ...args);
console.log(LOG: Exiting method ${methodName}.);
return result;
}
return replacementMethod;
}class Calculator {
@logged
add(a: number, b: number) {
return a + b;
}
}
总结
掌握这些高级 TypeScript 模式可以帮助你编写更类型安全、更可维护的代码。