# 十五.自定义集合操作

前言

# 1.Diff

类型的补集

let person1 = {
  name: "abc",
  age: 11,
  address: "dddd",
};
let person2 = {
  adresss: "dddd",
};

type DiffPerson = Diff<typeof person1, typeof person2>;
1
2
3
4
5
6
7
8
9
10
  • 实现原理
type Diff<T extends object, K extends Object> = Omit<T, keyof K>;
1

# 2.InterSection

类型的交集

let person1 = {
  name: "aaaa",
  age: 111,
  address: "bbbb",
};
let preson2 = {
  addresss: "bbbb",
};
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
11
12
13

# 3.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
8
9
10
11
12
13
14
  • 自定义
type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
1
type HexColorLine = Overwrite<Line, { color: number }>
1
  • 使用其他
type HexColorLine = Omit<Line, 'color'> & {
  color: number;
}
1
2
3

如果存在已有属性则使用新属性类型进行覆盖操作

# 4.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