
深入TypeScript:掌握现代TypeScript开发的进阶技巧
TypeScript已成为构建可扩展JavaScript应用程序的事实标准。本指南将深入探讨TypeScript的高级特性,助您提升开发技能,编写更安全可靠的代码。
1. 高级类型系统
灵活处理类型关系:
<code class="typescript">type IsArray<T> = T extends any[] ? true : false; type IsString<T> = T extends string ? true : false; // 使用示例 type CheckArray = IsArray<string>; // true type CheckString = IsString<string>; // true // 更复杂的条件类型 type UnwrapPromise<T> = T extends Promise<infer U> ? U : T; type ArrayElement<T> = T extends (infer U)[] ? U : never; // 使用示例 type PromiseString = UnwrapPromise<Promise<string>>; // string type NumberArray = ArrayElement<number[]>; // number</code>
利用字符串字面量提升类型安全性:
<code class="typescript">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<T extends string> = `on${Capitalize<T>}`;
type ButtonEvents = PropEventType<'click' | 'hover' | 'focus'>;
// 结果:'onclick' | 'onhover' | 'onfocus'</code>2. 高级泛型
创建灵活且类型安全的泛型接口:
<code class="typescript">interface Database<T extends { id: string }> {
find(id: string): Promise<T | null>;
create(data: Omit<T, 'id'>): Promise<T>;
update(id: string, data: Partial<T>): Promise<T>;
delete(id: string): Promise<boolean>;
}
// 实现示例
class MongoDatabase<T extends { id: string }> implements Database<T> {
constructor(private collection: string) {}
async find(id: string): Promise<T | null> {
// 实现
return null;
}
async create(data: Omit<T, 'id'>): Promise<T> {
// 实现
return { id: 'generated', ...data } as T;
}
async update(id: string, data: Partial<T>): Promise<T> {
// 实现
return { id, ...data } as T;
}
async delete(id: string): Promise<boolean> {
// 实现
return true;
}
}</code>高级类型转换:
<code class="typescript">type Getters<T> = {
[K in keyof T as `get${Capitalize<K & string>}`]: () => T[K]
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
// 结果:
// {
// getName: () => string;
// getAge: () => number;
// }
// 使用过滤器的键重映射
type FilteredKeys<T, U> = {
[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<Mixed, string>;
// 结果:{ name: string }</code>3. 高级装饰器
创建强大的元数据驱动装饰器:
<code class="typescript">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;
}
}</code>4. 高级实用程序类型
构建强大的类型转换:
<code class="typescript">// 深度 Partial 类型
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
// 深度 Required 类型
type DeepRequired<T> = {
[P in keyof T]-?: T[P] extends object ? DeepRequired<T[P]> : T[P];
};
// 深度 Readonly 类型
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
// 使用示例
interface Config {
server: {
port: number;
host: string;
options: {
timeout: number;
retries: number;
};
};
database: {
url: string;
name: string;
};
}
type PartialConfig = DeepPartial<Config>;
// 现在可以有部分嵌套对象
const config: PartialConfig = {
server: {
port: 3000
// host 和 options 可以省略
}
};</code>5. 类型安全的API模式
实现具有完整类型安全的构建器模式:
<code class="typescript">class RequestBuilder<T> {
private data: T;
constructor(data: T = {} as T) {
this.data = data;
}
with<K extends string, V>(
key: K,
value: V
): RequestBuilder<T & { [P in K]: V }> {
return new RequestBuilder({ ...this.data, [key]: value });
}
build(): T {
return this.data;
}
}
// 使用示例
const request = new RequestBuilder<{ url: string; method: string; headers: { 'content-type': string } }>()
.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 };
// }</code>6. 高级错误处理
创建强大的错误处理系统:
<code class="typescript">class Result<T, E extends Error = Error> {
private constructor(
private value: T | null,
private error: E | null
) {}
static ok<T>(value: T): Result<T, never> {
return new Result(value, null);
}
static err<E extends Error>(error: E): Result<never, E> {
return new Result(null, error);
}
map<U>(fn: (value: T) => U): Result<U, E> {
if (this.value === null) {
return new Result(null, this.error);
}
return new Result(fn(this.value), null);
}
mapError<F extends Error>(fn: (error: E) => F): Result<T, F> {
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<number, Error> {
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</code>总结
这些高级TypeScript模式展现了TypeScript在构建类型安全、易维护应用程序方面的强大能力。掌握这些概念,您可以更好地构建健壮的应用程序,充分发挥TypeScript类型系统的潜力。
更多资源
欢迎在评论区分享您对这些模式的经验!您在项目中最常用哪些高级TypeScript特性?
标签:#TypeScript #JavaScript #Web开发 #编程 #类型安全
以上就是高级 TypeScript:深入探讨现代 TypeScript 开发的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号