Question:
How to map an array of types to another array of types in TypeScript?

Problem

I want to make a class to wrap some primitive types into another such as:


class MyClass<T> {

    foo? : T

}


type Input = [string, number, boolean]


type Remap<T> = MyClass<T>


type Output = Remap<Input>  // <-- Now it's MyClass<Input>

// Can I make the Remap to infer an Output as the following?

// type Output = [MyClass<string>, MyClass<number>, MyClass<boolean>]


But I don't know how to, if doable, make a proper Remap type to make the Output match my expectation.


>Playground


Solution

Yes, in fact, this can be done with a plain >mapped type:


type Remap<T> = { [I in keyof T]: MyClass<T[I]> }


type Output = Remap<Input>

//   ^? type Output = [MyClass<string>, MyClass<number>, MyClass<boolean>]


Mapped types that act on keyof T where T is a generic type parameter automatically >transform arrays to arrays and tuples to tuples.


>Playground link to code


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers