1

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?

2
  • Can you put some example data.
    – Vishwanath
    Commented Aug 4, 2022 at 12:41
  • There's no data involved in this question. It's all about the types.
    – zkldi
    Commented Aug 4, 2022 at 12:44

1 Answer 1

2
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>>() {
  ...
}
3
  • Is there a way to make this work for tuple types aswell? extends Array doesn't work for non-arrays, for some reason [1, 2] doesn't extend array. Is there a type that includes types like [1, 2], but isn't Iterable? Iterable doesn't have array properties on it like .map, so it ain't right here.
    – zkldi
    Commented Aug 4, 2022 at 12:54
  • I believe there are a bit too many brackets in that function definition, no?
    – Behemoth
    Commented Aug 4, 2022 at 12:58
  • Update: I believe changing extends Array to extends ReadonlyArray was what I needed for that functionality. I was using as const to create fixed-type tuples and that was making it readonly.
    – zkldi
    Commented Aug 4, 2022 at 13:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.