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. Commented Aug 4, 2022 at 12:41
  • There's no data involved in this question. It's all about the types. 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>>() {
  ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I believe there are a bit too many brackets in that function definition, no?
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.

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.