Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to flatten an Array of Array type?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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?

>Solution :

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>>() {
  ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading