[SOLVED] Create type having common props from other types and other optional

Issue

I have following three interfaces:

type A = {
    x: string
    y: string
}

type B = {
    y: string
}

type C = {
    z: string;
    y: string;
}

There are common required properties here. And there’re required properties which are not part of the rest of 2 types. So, my question is:

Is there way to create type that unites common props and makes other properties optional? E.g.:

type D = {
    y: string
    x?: string
    z?: string
}

Any ideas?

Solution

There’s quite a few ways to do this, but one solution would be to create a type Pick<T1, keyof T1 & keyof T2 & keyof T3> that has the properties shared by three types T1 to T3, and intersect it with an object Partial<T1 & T2 & T3> that has optional properties for any properties in T1 to T3.

type CommonRequiredRestOptional<T1, T2, T3> =
  Pick<T1, keyof T1 & keyof T2 & keyof T3> & Partial<T1 & T2 & T3>

The partial object will also contain the required properties, but because of the intersection these stay required (T & (T | undefined) is T).

A helper TopLevelNormalize can be used to show the actual object type rather than Pick<A, "y"> & Partial<A & B & C>:

type TopLevelNormalize<T> = T extends infer S ? {[K in keyof S]: S[K]} : never;

type Test = TopLevelNormalize<CommonRequiredRestOptional<A, B, C>>
// type Test = { y: string; x?: string | undefined; z?: string | undefined;}

TypeScript playground

Answered By – Oblosys

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *