0

Let's say I have this:

type CoolTuple = [string, number, boolean]

And, I want to map that type using some generic:

type CoolGeneric<T extends any[]> = ... 

Such that:

CoolGeneric<CoolType> is [Wrapper<string>, Wrapper<number>, Wrapper<boolean>] 

What would I do?

1 Answer 1

2

You want a mapped type:

type CoolGeneric<T extends any[]> = { [K in keyof T]: Wrapper<T[K]> }

Basically, for each key (indices of a tuple are keys), declare the type to be something that uses the property type T[K].

Playground

Sign up to request clarification or add additional context in comments.

5 Comments

Oh, I didn't realize this worked for arrays.
A tuple is basically just an object with sequential integer keys.
Yeah, makes sense.
"a tuple is basically just an object with sequential integer keys"... well, it also has non-integer keys like "length" and "push" and you don't want to map those (so that you get a length of type Wrapper<number> and a push of type Wrapper<(...items: (string | number | boolean)[]) => number>). TypeScript 3.1 added support to have mapped types turn arrays/tuples into arrays/tuples and that change stopped treating them like "just an object".
@AlexWayne I just started running into a situation where this creates unions of the wrapper types as opposed to interpreting them as a progressive tuple? Any idea why this could be?

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.