深入TypeScript:掌握现代TypeScript开发的进阶技巧
TypeScript已成为构建可扩展JavaScript应用程序的事实标准。本指南将深入探讨TypeScript的高级特性,助您提升开发技能,编写更安全可靠的代码。
1. 高级类型系统
条件类型
灵活处理类型关系:
type IsArray = T extends any[] ? true : false;type IsString = T extends string ? true : false;// 使用示例type CheckArray = IsArray; // truetype CheckString = IsString; // true// 更复杂的条件类型type UnwrapPromise = T extends Promise ? U : T;type ArrayElement = T extends (infer U)[] ? U : never;// 使用示例type PromiseString = UnwrapPromise<Promise>; // stringtype NumberArray = ArrayElement; // number
登录后复制
模板字面量类型
利用字符串字面量提升类型安全性:
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';type ApiEndpoint = '/users' | '/posts' | '/comments';type ApiRoute = `${HttpMethod} ${ApiEndpoint}`;// 有效路由const validRoute: ApiRoute = 'GET /users';const validRoute2: ApiRoute = 'POST /posts';// 错误:类型 '"PATCH /users"' 不可赋值给类型 'ApiRoute'// const invalidRoute: ApiRoute = 'PATCH /users';// 动态模板字面量类型type PropEventType = `on${Capitalize}`;type ButtonEvents = PropEventType;// 结果:'onclick' | 'onhover' | 'onfocus'
登录后复制
2. 高级泛型
通用约束和默认值
创建灵活且类型安全的泛型接口:
interface Database { find(id: string): Promise; create(data: Omit): Promise; update(id: string, data: Partial): Promise; delete(id: string): Promise;}// 实现示例class MongoDatabase implements Database { constructor(private collection: string) {} async find(id: string): Promise { // 实现 return null; } async create(data: Omit): Promise { // 实现 return { id: 'generated', ...data } as T; } async update(id: string, data: Partial): Promise { // 实现 return { id, ...data } as T; } async delete(id: string): Promise { // 实现 return true; }}
登录后复制
映射类型和键重映射
高级类型转换:
type Getters = { [K in keyof T as `get${Capitalize}`]: () => T[K]};interface Person { name: string; age: number;}type PersonGetters = Getters;// 结果:// {// getName: () => string;// getAge: () => number;// }// 使用过滤器的键重映射type FilteredKeys = { [K in keyof T as T[K] extends U ? K : never]: T[K]};interface Mixed { name: string; count: number; isActive: boolean; data: object;}type StringKeys = FilteredKeys;// 结果:{ name: string }
登录后复制
3. 高级装饰器
自定义属性装饰器
创建强大的元数据驱动装饰器:
function ValidateProperty(validationFn: (value: any) => boolean) { return function (target: any, propertyKey: string) { let value: any; const getter = function () { return value; }; const setter = function (newVal: any) { if (!validationFn(newVal)) { throw new Error(`Invalid value for ${propertyKey}`); } value = newVal; }; Object.defineProperty(target, propertyKey, { get: getter, set: setter, enumerable: true, configurable: true, }); };}class User { @ValidateProperty((value) => typeof value === 'string' && value.length > 0) name: string; @ValidateProperty((value) => typeof value === 'number' && value >= 0) age: number; constructor(name: string, age: number) { this.name = name; this.age = age; }}
登录后复制
4. 高级实用程序类型
自定义实用程序类型
构建强大的类型转换:
// 深度 Partial 类型type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P];};// 深度 Required 类型type DeepRequired = { [P in keyof T]-?: T[P] extends object ? DeepRequired : T[P];};// 深度 Readonly 类型type DeepReadonly = { readonly [P in keyof T]: T[P] extends object ? DeepReadonly : T[P];};// 使用示例interface Config { server: { port: number; host: string; options: { timeout: number; retries: number; }; }; database: { url: string; name: string; };}type PartialConfig = DeepPartial;// 现在可以有部分嵌套对象const config: PartialConfig = { server: { port: 3000 // host 和 options 可以省略 }};
登录后复制
5. 类型安全的API模式
类型安全的构建器模式
实现具有完整类型安全的构建器模式:
class RequestBuilder { private data: T; constructor(data: T = {} as T) { this.data = data; } with( key: K, value: V ): RequestBuilder { return new RequestBuilder({ ...this.data, [key]: value }); } build(): T { return this.data; }}// 使用示例const request = new RequestBuilder() .with('url', 'https://api.example.com') .with('method', 'GET') .with('headers', { 'content-type': 'application/json' }) .build();// 类型正确推断type Request = typeof request;// {// url: string;// method: string;// headers: { 'content-type': string };// }
登录后复制
6. 高级错误处理
类型安全的错误处理
创建强大的错误处理系统:
class Result { private constructor( private value: T | null, private error: E | null ) {} static ok(value: T): Result { return new Result(value, null); } static err(error: E): Result { return new Result(null, error); } map(fn: (value: T) => U): Result { if (this.value === null) { return new Result(null, this.error); } return new Result(fn(this.value), null); } mapError(fn: (error: E) => F): Result { if (this.error === null) { return new Result(this.value, null); } return new Result(null, fn(this.error)); } unwrap(): T { if (this.value === null) { throw this.error; } return this.value; }}// 使用示例function divide(a: number, b: number): Result { if (b === 0) { return Result.err(new Error('Division by zero')); } return Result.ok(a / b);}const result = divide(10, 2) .map(n => n * 2) .unwrap(); // 10
登录后复制
总结
这些高级TypeScript模式展现了TypeScript在构建类型安全、易维护应用程序方面的强大能力。掌握这些概念,您可以更好地构建健壮的应用程序,充分发挥TypeScript类型系统的潜力。
更多资源
TypeScript 官方文档深入学习TypeScriptTypeScript GitHub 仓库
欢迎在评论区分享您对这些模式的经验!您在项目中最常用哪些高级TypeScript特性?
标签:#TypeScript #JavaScript #Web开发 #编程 #类型安全
以上就是高级 TypeScript:深入探讨现代 TypeScript 开发的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2643927.html