Home > Net >  What does this line " export type Replace<T, R> = Omit<T, keyof R> & R; " do i
What does this line " export type Replace<T, R> = Omit<T, keyof R> & R; " do i

Time:12-22

With my current knowledge, I am not able to understand what the Replace type is.

I did read the typescript documentation and learned part of what's happening in that line but it still was not enough for me to understand that.

CodePudding user response:

The type Replace is replacing properties in T, with properties in R.

To break it down:

  1. Omit<T, keyof R> removes properties from T those with same name as properties in R.
  2. Then & R intersects the resulting type from (1) with R. That means it adds the properties in R to the resulting type.

This may seem weird in that it re-adds the same properties to the resulting type those it removed earlier. But I suspect this was done to replace the type of the properties. Here is an example.

type Replace<T, R> = Omit<T, keyof R> & R;

type A = {
  prop1: string,
  prop2: string,
  prop3: string,
  prop4: string
};

type B = {
  prop3: number,
  prop4: number
};


type X = Replace<A, B>;

const x: X = {
  prop1: '1',
  prop2: '2',
  prop3: 3,
  prop4: 4
}

CodePudding user response:

It remove the common key of T and R from T, then intersect the result with R

enter image description here

as you can see, the common key is b, b of A is string, now it is boolean(from b of C)

playground

  • Related