泛型与类型编程
约 283 字小于 1 分钟
2026-02-09
泛型函数
泛型用于“把类型当参数传入”。
function identity<T>(value: T): T {
return value
}
const n = identity(123) // T 推导为 number
const s = identity<string>('hello')泛型接口与泛型类
interface ApiResponse<T> {
code: number
data: T
}
class Box<T> {
constructor(public value: T) {}
}
const userBox = new Box({ id: 1, name: 'zjs' })泛型约束(extends)
interface HasLength {
length: number
}
function printLength<T extends HasLength>(input: T) {
console.log(input.length)
}keyof + 泛型关联
function getProp<O, K extends keyof O>(obj: O, key: K): O[K] {
return obj[key]
}
const user = { id: 1, name: 'zjs' }
const name = getProp(user, 'name')条件类型
type IsString<T> = T extends string ? true : false
type A = IsString<'x'> // true
type B = IsString<number> // falseinfer 推断
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T
type C = UnwrapPromise<Promise<string>> // string映射类型
type Nullable<T> = {
[K in keyof T]: T[K] | null
}
interface User {
id: number
name: string
}
type NullableUser = Nullable<User>映射修饰符
type MutableRequired<T> = {
-readonly [K in keyof T]-?: T[K]
}常用内置工具类型
Partial<T>:全部可选Required<T>:全部必填Readonly<T>:全部只读Pick<T, K>:挑选字段Omit<T, K>:排除字段Record<K, V>:键值映射
type UserPatch = Partial<User>
type UserName = Pick<User, 'name'>