5

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!

0

2 Answers 2

4

I believe this does what you need:

type SingleContainer = {[P in keyof MultiContainer]: MultiContainer[P][0]}
Sign up to request clarification or add additional context in comments.

Comments

2

From TS 2.8 it's possible to use infer keyword:

type SingleContainer = {
  [P in keyof MultiContainer]: MultiContainer[P] extends (infer T)[] ? T : never
};

1 Comment

Quite genius! This allows you to construct a Flat<T> type: type Flat<T> = { [P in keyof T]: T[P] extends (infer A)[] ? A : T[P]; }. Usage: interface MixedContainer { Item1: T1; Item2: T2[] }; type FlatContainer = Flat<MixedContainer>; // { Item1: T1; Item2: T2 } Throw in some string template typing and you can even go from { Items: T1[] } to { Item: T1 }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.