4

I'm trying to achieve something like clone of one array type with specified value types as array with functions which return specified values.

Say we have array tuple like:

[string, number]

And what I want is to get generated type from it like:

[() => string, () => number]

What I've tried was to make type alias with keyof usage:

type tupleTransform<T extends Array<any>> = { [U in keyof T ]: (() => T[U]) };

And it almost worked except that it also checks for methods of Array so if I'll make:

const tupleTransformer: tupleTransform<[string, number]> = [() => 'a', () => 5]

It will fire me error that eg some method is not returning proper type

1 Answer 1

5

I think you can do something like this:

type TupleTransform<T extends any[]> = { [K in keyof T]:
    K extends "length" ? T[K] :
    K extends keyof any[] ? Array<() => T[number]>[K] :
    () => T[K] 
}

It uses conditional types to distinguish between the array methods and the tuple numeric-string indices.

Let's make sure it works:

const tupleTransformer: TupleTransform<[string, number]> = [() => 'a', () => 5] //okay
const t0: () => string = tupleTransformer[0]
const t1: () => number = tupleTransformer[1]
const len: 2 = tupleTransformer.length;
const mapped: (string | number)[] = tupleTransformer.map(x => x()); 

Looks okay to me. It might differ from a "real" tuple in some subtle way, so caveat emptor. Hope that helps. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

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.