4

Let's say we have two interfaces First and Second:

interface First {
  a: string;
  b: number;
}

interface Second {
  b: number;
  c: Date;
}

With intersections it is possible to merge two interfaces:

type FirstSecond = First & Second // {a: string, b: number, c: Date}

But is it possible to make an inner join, so the resultant interface only consists of properties that are declared in both interfaces:

type FirstSecond = First /*inner join here*/ Second // {b: number}

This could especially be helpful for generic types.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ysfaran
  • 5,189
  • 3
  • 21
  • 51
  • Why don't you extract the common interface? – jonrsharpe Jul 30 '19 at 09:02
  • 1
    https://stackoverflow.com/questions/47375916/typescript-how-to-create-type-with-common-properties-of-two-types – Roberto Zvjerković Jul 30 '19 at 09:03
  • 1
    @jonrsharpe idk what you telling me to do? If it would be that simple for me I would not ask a question here. If you mean that I should declare a third interface like `{ b: number }` then it's not answering my question because I wanted to have a generic solution (see last sentence). – ysfaran Jul 30 '19 at 10:17
  • Yes, that's exactly what I mean, extract a third interface with the commonalities. – jonrsharpe Jul 30 '19 at 10:18

1 Answers1

6

You can use Pick to take the common properties from the intersection. To get the common properties, you can use the Extract conditional type to filter the keys of one type by the keys of the other:


interface First {
  a: string;
  b: number;
}

interface Second {
  b: number;
  c: Date;
}


type IntersectByProperties<T, U> = Pick<T & U, Extract<keyof T, keyof U>>

type R = IntersectByProperties<First, Second>

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357