手动实现Omit, Pick, Exclude, Extract工具类型
2024/04/18 2 mins read See this issue
# Typescript
Back
To Top
Omit
(省略):用于从数据集中省略或删除特定的项目或属性,以过滤掉不需要的信息。Pick
(选择):与Omit相反,它用于从数据集中选择特定的项目或属性,并将它们提取出来,以便后续处理。Exclude
(排除):与Omit类似,用于排除数据集中的特定项目或属性,但通常更强调的是根据某些条件或规则进行排除。Extract
(提取):用于从数据集中提取出特定的信息或特征,通常是通过某种模式匹配或者规则来实现。
interface User {
id: number;
age: number;
name: string;
}
// Pick
type MyPick<T, K extends keyof T> = {
[P in K]: T[P]
}
type demo = MyPick<User, "id" | "name">
// Exclude
type MyExclude<T, U> = T extends U ? never : T
// Extract
type MyExtract<T, U> = T extends U ? T : never
type key1 = 'id'|'name'
type key2 = 'id'
type demo2 = MyExclude<key1,key2>
type demo3 = MyExtract<key1,key2>
// Omit
type MyOmit<T, K extends keyof T> = {
[P in MyExclude<keyof T, K>]: T[P]
}
type demo4 = MyOmit<User, 'name'>
// Omit第二种写法
type MyOmit2<T, K extends keyof T> = MyPick<T, MyExclude<keyof T, K>>
type demo5 = MyOmit2<User, 'name'>