元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
TypeScript环境准备
安装与配置
第一个TS程序
编译流程解析
▶
基础类型系统
类型注解语法
原始类型定义
数组与元组
接口与对象
▶
高级类型系统
泛型编程
条件类型
映射类型
类型推断
类型保护
高级类型工具
▶
函数开发
函数类型声明
可选参数与默认值
箭头函数应用
函数重载
泛型函数
▶
类与面向对象
类的定义
继承与修饰符
存取器使用
抽象类与接口
泛型类与抽象类
访问修饰符与属性
▶
模块化开发
模块导入导出
类型声明文件
命名空间
模块解析策略
▶
工程实践
tsconfig详解
常见编译选项
项目构建配置
代码组织最佳实践
单元测试
调试技巧
▶
常见问题
类型错误处理
类型断言技巧
类型兼容性
版本迁移指南
发布时间:
2025-03-31 09:41
↑
☰
# 高级类型工具 TypeScript提供了一系列内置的工具类型,它们可以帮助我们进行类型转换和操作。本文将详细介绍这些工具类型的使用方法和应用场景。 ## 常用工具类型 ### Partial<T> 将类型的所有属性变为可选: ```typescript interface Todo { title: string; description: string; completed: boolean; } type PartialTodo = Partial<Todo>; // 等价于: // { // title?: string; // description?: string; // completed?: boolean; // } function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) { return { ...todo, ...fieldsToUpdate }; } ``` ### Required<T> 将类型的所有属性变为必需: ```typescript interface Props { a?: number; b?: string; } const obj: Required<Props> = { a: 5, b: 'hello' }; // 正确 // const obj2: Required<Props> = { a: 5 }; // 错误: 缺少属性'b' ``` ### Readonly<T> 将类型的所有属性变为只读: ```typescript interface Config { host: string; port: number; } const config: Readonly<Config> = { host: 'localhost', port: 3000 }; // config.port = 4000; // 错误: 无法分配到'port',因为它是只读属性 ``` ### Record<K,T> 创建一个具有指定键类型K和值类型T的对象类型: ```typescript type PageInfo = { title: string; url: string; }; type Pages = Record<string, PageInfo>; const pages: Pages = { home: { title: 'Home', url: '/' }, about: { title: 'About', url: '/about' } }; ``` ### Pick<T,K> 从类型T中选择一组属性K: ```typescript interface User { id: number; name: string; email: string; age: number; } type UserBasicInfo = Pick<User, 'name' | 'email'>; // 等价于: // { // name: string; // email: string; // } ``` ### Omit<T,K> 从类型T中排除一组属性K: ```typescript type UserPublicInfo = Omit<User, 'id' | 'age'>; // 等价于: // { // name: string; // email: string; // } ``` ### Exclude<T,U> 从类型T中排除可以赋值给类型U的类型: ```typescript type T0 = Exclude<'a' | 'b' | 'c', 'a'>; // 'b' | 'c' type T1 = Exclude<string | number | (() => void), Function>; // string | number ``` ### Extract<T,U> 从类型T中提取可以赋值给类型U的类型: ```typescript type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'>; // 'a' type T1 = Extract<string | number | (() => void), Function>; // () => void ``` ### NonNullable<T> 从类型T中排除null和undefined: ```typescript type T0 = NonNullable<string | number | undefined>; // string | number type T1 = NonNullable<string[] | null | undefined>; // string[] ``` ## 实际应用场景 ### 1. 表单处理 ```typescript interface UserForm { username: string; password: string; email: string; age: number; } // 部分更新表单 function updateUserForm(userId: string, updates: Partial<UserForm>) { // 实现部分更新逻辑 } // 表单验证规则 type ValidationRules = Record<keyof UserForm, { required?: boolean; minLength?: number; maxLength?: number; pattern?: RegExp; }>; ``` ### 2. API响应处理 ```typescript interface ApiResponse<T> { data: T; status: number; message: string; timestamp: number; } // 提取API响应中的数据部分 type ApiData<T> = Extract<T, { data: any }>['data']; // 移除响应中的内部字段 type PublicApiResponse<T> = Omit<ApiResponse<T>, 'timestamp'>; ``` ### 3. 配置对象处理 ```typescript interface Config { api: { endpoint: string; timeout: number; retries: number; }; debug: boolean; cache: { enabled: boolean; ttl: number; }; } // 创建只读配置 type ReadonlyConfig = Readonly<Config>; // 提取API相关配置 type ApiConfig = Pick<Config, 'api'>; // 创建可选配置 type OptionalConfig = Partial<Config>; ``` ## 最佳实践 1. **组合使用工具类型**: ```typescript // 创建一个只读且所有属性都必填的类型 type StrictConfig = Readonly<Required<Config>>; // 创建一个部分可选的类型 type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; ``` 2. **使用类型别名提高可读性**: ```typescript type StringMap<T> = Record<string, T>; type NonEmptyArray<T> = [T, ...T[]]; type Nullable<T> = T | null; ``` 3. **创建自定义工具类型**: ```typescript // 深度Partial类型 type DeepPartial<T> = { [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]; }; // 移除类型中的只读属性 type Mutable<T> = { -readonly [P in keyof T]: T[P]; }; ``` ## 总结 TypeScript的工具类型是一组强大的类型转换工具,它们可以帮助我们: - 转换和操作已有类型 - 提高代码的类型安全性 - 减少重复的类型定义 - 实现更灵活的类型系统 合理使用这些工具类型可以让我们的代码更加类型安全、可维护,同时减少重复的类型定义。在实际开发中,我们应该根据具体需求选择合适的工具类型,并且可以通过组合使用它们来创建更复杂的类型转换。