Home > Enterprise >  Is there a way to flatten an Array of Array type?
Is there a way to flatten an Array of Array type?

Time:08-05

I have a function that takes in a type like:

type Input = [Array<string>, Array<number>, Array<boolean>];

It returns output in the form:

Array<[string, number, boolean]>

Effectively flattening the type out of the array.


Is there a way to achieve this with generics? My function signature at the moment looks like:

function foo<T extends Array<Array<unknown>>>(arrays: T) {

}

Assumedly, I need to apply some sort of transform onto T, what transform do I need?

CodePudding user response:

type Unarrayify<T> = { [K in keyof T]: T[K] extends Array<infer E> ? E : T[K] };

type MyType = Unarrayify<[Array<number>, Array<string>, Array<boolean>]>; // [number, string, boolean]

function foo<T>(arrays: T): Array<Unarrayify<T>>() {
  ...
}
  • Related