It seems impossible to determine the order of the array args
. When trying to spread the args
into an array and assigning it a type of Array<T[keyof T]>
, TypeScript will merge all the types together as it cannot accurately narrow down the type for each individual item in the array. You can check out this behavior on the playground.
function fun(...args: Array<T[keyof T]>) {
const [a, b, c, d] = args;
}
https://i.stack.imgur.com/Kao7a.png
The inferred types show that args
is essentially evaluated as
<number | string | boolean>[]
.
To address this issue, you can explicitly specify a fixed number of arguments by passing all 4 arguments as a single object. Check out the modified code on the playground.
function fun({ ...args }: T) {
const { a, b, c, d } = args;
}
fun({
a: 'a',
b: 'b',
c: 8,
d: true
});
By deconstructing the args
object, you will get the correct typings:
https://i.stack.imgur.com/R01i6.png