Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to normalize nested type transform in typescript?

I’m working on a type transforming library.
And I’m trying to transform a type into another type.

Given a simple example here.

interface Struct {
    a: {
        x: number;
        y: number;
    };
    b: string;
}

type OmitDeepX<T> = { [K in keyof T]: Omit<T[K], 'x'> };

export type TransformedStruct1 = OmitDeepX<Struct>;

VSCode output me this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

While the type is correct but as a user of this library I expected to see a normalized type like below

type TransformedStruct = {
   a: {
       y: number;
   };
   b: string;
}

And this is what I saw many times in other projects e.g. trpc, zod

But how could I achieve this?

>Solution :

Just wrap your type with this prettify helper

type Prettify<T> = T extends object ?  {[K in keyof T]: Prettify<T[K]>} : T

type OmitDeepX<T> = { [K in keyof T]: Omit<T, 'x'> };

type PrettyOmitDeep<T> = Prettify<OmitDeepX<T>>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading