Search code examples
typescriptinterfaceextends

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?


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