TypeScript类型体操实战
通过实际案例学习TypeScript的高级类型技巧,掌握类型编程的精髓
2024年2月1日
2 min read
TypeScript类型系统进阶
什么是类型体操
类型体操是指使用TypeScript的类型系统来实现复杂的类型转换和类型推导。
常用工具类型
1. Pick和Omit
interface User {
id: number
name: string
email: string
password: string
}
// 只选择部分属性
type PublicUser = Pick<User, 'id' | 'name' | 'email'>
// 排除部分属性
type UserWithoutPassword = Omit<User, 'password'>2. Record
type Role = 'admin' | 'user' | 'guest'
type Permissions = Record<Role, string[]>
const permissions: Permissions = {
admin: ['read', 'write', 'delete'],
user: ['read', 'write'],
guest: ['read']
}高级类型技巧
条件类型
type IsString<T> = T extends string ? true : false
type A = IsString<string> // true
type B = IsString<number> // false映射类型
type Readonly<T> = {
readonly [P in keyof T]: T[P]
}
type ReadonlyUser = Readonly<User>实战案例
深度只读类型
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object
? DeepReadonly<T[P]>
: T[P]
}总结
TypeScript的类型系统非常强大,掌握这些技巧能让你的代码更加类型安全。