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

Is is possible to create a new TypeScript interface of array types from an existing interface of non-array types?

I have [something akin to] this:

type Thunk = 'uh' | 'um' | 'dunno mate';
interface Whatever {
    meh: Thunk;
}

And that’s all good my bro. But then later I need this:

interface LoadsOfWhatever {
    meh: Thunk[];
}

Is there a way to extend/Pick/etc it from Whatever or will this just need to be literally created?

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

>Solution :

This can be done with mapped types. These let you calculate a new type from an old one, applying some transformation to every property. Here’s how it looks to turn every property into an array:

type Thunk = 'uh' | 'um' | 'dunno mate';
interface Whatever {
    meh: Thunk;
}

type LoadsOfWhatever = {
  [key in keyof Whatever]: Whatever[key][];
}

Obviously it’s wordier than the original code if all you have is the one meh property. But if Whatever had 50 properties, you wouldn’t need to change LoadsOfWhatever; it would turn all 50 properties into arrays

Playground Link

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