TypeScript 高级模式与实践
张三
4 min read
TypeScript设计模式类型系统
TypeScript 高级模式与实践
本文将深入探讨 TypeScript 的高级特性和常用设计模式,帮助你编写更安全、更优雅的代码。
1. 高级类型系统
1.1 条件类型
typescript6 行代码1type IsString<T> = T extends string ? true : false; 2type Result1 = IsString<"hello">; // true 3type Result2 = IsString<42>; // false 4 5// 实际应用 6type NonNullable<T> = T extends null | undefined ? never : T;
1.2 映射类型
typescript12 行代码1type Readonly<T> = { 2 readonly [P in keyof T]: T[P]; 3}; 4 5type Partial<T> = { 6 [P in keyof T]?: T[P]; 7}; 8 9// 高级映射 10type DeepReadonly<T> = { 11 readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P]; 12};
2. 类型推断优化
2.1 泛型约束
typescript14 行代码1interface HasLength { 2 length: number; 3} 4 5function logLength<T extends HasLength>(arg: T): number { 6 console.log(arg.length); 7 return arg.length; 8} 9 10// 使用 11logLength("hello"); // 5 12logLength([1, 2, 3]); // 3 13logLength({ length: 10 }); // 10 14// logLength(42); // Error!
2.2 类型守卫
typescript21 行代码1interface Bird { 2 fly(): void; 3 layEggs(): void; 4} 5 6interface Fish { 7 swim(): void; 8 layEggs(): void; 9} 10 11function isFish(pet: Fish | Bird): pet is Fish { 12 return (pet as Fish).swim !== undefined; 13} 14 15function move(pet: Fish | Bird) { 16 if (isFish(pet)) { 17 pet.swim(); 18 } else { 19 pet.fly(); 20 } 21}
3. 高级设计模式
3.1 Builder 模式
typescript34 行代码1class RequestBuilder { 2 private url: string = ""; 3 private method: "GET" | "POST" = "GET"; 4 private headers: Record<string, string> = {}; 5 private body: unknown; 6 7 setUrl(url: string): this { 8 this.url = url; 9 return this; 10 } 11 12 setMethod(method: "GET" | "POST"): this { 13 this.method = method; 14 return this; 15 } 16 17 setHeader(key: string, value: string): this { 18 this.headers[key] = value; 19 return this; 20 } 21 22 setBody<T>(body: T): this { 23 this.body = body; 24 return this; 25 } 26 27 build(): Request { 28 return new Request(this.url, { 29 method: this.method, 30 headers: this.headers, 31 body: JSON.stringify(this.body), 32 }); 33 } 34}
3.2 工厂模式
typescript28 行代码1interface Logger { 2 log(message: string): void; 3} 4 5class ConsoleLogger implements Logger { 6 log(message: string): void { 7 console.log(message); 8 } 9} 10 11class FileLogger implements Logger { 12 log(message: string): void { 13 // 写入文件逻辑 14 } 15} 16 17class LoggerFactory { 18 static createLogger(type: "console" | "file"): Logger { 19 switch (type) { 20 case "console": 21 return new ConsoleLogger(); 22 case "file": 23 return new FileLogger(); 24 default: 25 throw new Error("Unknown logger type"); 26 } 27 } 28}
4. 性能优化技巧
4.1 类型缓存
typescript18 行代码1// 不好的写法 2type DeepPartial<T> = { 3 [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]; 4}; 5 6// 好的写法 7interface CachedType<T> { 8 type: T; 9} 10 11type DeepPartialCached<T> = 12 T extends CachedType<infer U> 13 ? DeepPartial<U> 14 : { 15 [P in keyof T]?: T[P] extends object 16 ? DeepPartialCached<CachedType<T[P]>> 17 : T[P]; 18 };
4.2 条件类型分发
typescript8 行代码1type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( 2 k: infer I 3) => void 4 ? I 5 : never; 6 7type Result = UnionToIntersection<{ a: string } | { b: number }>; 8// Result = { a: string } & { b: number }
5. 实战应用
5.1 API 类型安全
typescript24 行代码1type ApiResponse<T> = { 2 data: T; 3 status: number; 4 message: string; 5}; 6 7type ApiEndpoints = { 8 "/users": { 9 get: ApiResponse<User[]>; 10 post: ApiResponse<User>; 11 }; 12 "/posts": { 13 get: ApiResponse<Post[]>; 14 post: ApiResponse<Post>; 15 }; 16}; 17 18async function apiRequest< 19 T extends keyof ApiEndpoints, 20 M extends keyof ApiEndpoints[T], 21>(endpoint: T, method: M): Promise<ApiEndpoints[T][M]> { 22 // 实现细节... 23 return {} as ApiEndpoints[T][M]; 24}
6. 总结
TypeScript 的类型系统非常强大,通过合理使用这些高级特性,我们可以:
- 提高代码的类型安全性
- 改善开发体验
- 减少运行时错误
- 提高代码可维护性
参考资料: