Appearance
15.自定义类型
一.Diff实现
求两个对象不同的部分
let person1 = {
name: 'zhufeng',
age: 11,
address: '回龙观'
}
let person2 = {
address: '回龙观',
}
type Diff<T extends object,K extends Object> = Omit<T,keyof K>
type DiffPerson = Diff<typeof person1,typeof person2>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
二.InterSection交集
let person1 = {
name: 'zhufeng',
age: 11,
address: '回龙观'
}
let person2 = {
address: '回龙观',
}
type InterSection<T extends object, K extends object> = Pick<T, Extract<keyof T, keyof K>>
type InterSectionPerson = InterSection<typeof person1, typeof person2>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
三.Overwrite属性覆盖
type OldProps = { name: string, age: number, visible: boolean };
type NewProps = { age: string, other: string };
type Diff<T extends object,K extends Object> = Omit<T,keyof K>
type InterSection<T extends object, K extends object> = Pick<T, Extract<keyof T, keyof K>>
type Overwrite<T extends object, K extends object, I = Diff<T,K> & InterSection<K,T>> = Pick<I,keyof I>
type ReplaceProps = Overwrite<OldProps, NewProps>
1
2
3
4
5
6
7
2
3
4
5
6
7
如果存在已有属性则使用新属性类型进行覆盖操作
四.Merge对象合并
type Compute<A extends any> = { [K in keyof A]: A[K] };
type Merge<T, K> = Compute<Omit<T, keyof K> & K>;
type MergeObj = Merge<OldProps,NewProps>
1
2
3
2
3
将两个对象类型进行合并操作