Liero
Liero

Reputation: 27348

How to pick common properties from two types?

I want to create type by selecting only members that are present in both types:

interface A {
    X: number;
    Y: number;
}
interface B {
    Y: number;
    Z: number;
}

type C = Common<A, B>; // { Y: number; }

Is there built-in utility type, proposition or commonly use pattern to achieve this?

Note: I was able to write following utility type, but I consider it quite difficult to reason about

type Common<T1, T2> = Omit<T1, keyof Omit<T1, keyof T2>>

However, is there something

Upvotes: 5

Views: 1592

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25800

You may find this easier to read:

type C = Pick<A | B, keyof A & keyof B>; // { Y: number; }

It picks (Pick) common properties (keyof A & keyof B) from the sum of A and B (A | B).

Upvotes: 6

Related Questions