I’m trying to write typing for a function I’m writing.
I made it more simple to understand using this straightforward code example:
const getValues: <T extends Array<() => any>>(
...args: T
) => T extends Array<() => infer R> ? R[] : null = (...args) =>
args.map((arg) => arg());
const values = getValues(
() => "a",
() => 123
);
I want values
to be of type [string, number]
but instead it’s of type (string|number)[]
2
Answers
Found it!
To ensure that the
values
array is inferred as[string, number]
instead of(string|number)[]
, you can update the typing of yourgetValues
function. Here’s an adjusted version of your code:By using a mapped type
{ [K in keyof T]: R }
, we ensure that the resulting type ofgetValues
is an array with the same length as the input array, where each element has the inferred typeR
. In this case,R
will be inferred asstring
for the first function andnumber
for the second function, resulting in the desired type[string, number]
for thevalues
variable.