泛型是 TypeScript 最强大的特性之一,它允许我们编写灵活且类型安全的代码。
// 泛型函数
function identity(arg: T): T {
return arg
}
// 泛型接口
interface Repository {
findById(id: string): Promise
findAll(): Promise
create(data: Omit): Promise
update(id: string, data: Partial): Promise
delete(id: string): Promise
}
type IsString = T extends string ? true : false
type A = IsString<'hello'> // true
type B = IsString<42> // false
// 内置条件类型
type Exclude = T extends U ? never : T
type Extract = T extends U ? T : never
type NonNullable = T extends null | undefined ? never : T
type Readonly = {
readonly [P in keyof T]: T[P]
}
type Partial = {
[P in keyof T]?: T[P]
}
// 实用工具类型
type Optional = Omit & Partial>
type EventName = 'click' | 'focus' | 'blur'
type EventHandler = `on${Capitalize}`
// 'onClick' | 'onFocus' | 'onBlur'
TypeScript 的类型系统非常强大,合理使用高级类型可以让代码更加安全和可维护。