Search code examples
typescriptmapped-types

TypeScript Mapped Types: Get element type of array


Suppose having a container type with array properties of unknown/generated types T1, T2, etc. (short T*):

interface MultiContainer
{
    Item1: T1[];
    Item2: T2[];
    ...
}

Is it possible to derive the following type using mapped types:

interface SingleContainer
{
    Item1: T1;
    Item2: T2;
    ...
}

I'm looking for some expression like:

type SingleContainer =
    { [ P in keyof MultiContainer ]: MultiContainer[P] }
                                            └─────────── returns T*[] instead of T*  

MultiContainer[P]returns the types T*[] but I need an expression that returns T*

Thanks in advance!


Solution

  • I believe this does what you need:

    type SingleContainer = {[P in keyof MultiContainer]: MultiContainer[P][0]}