TypeScript Array generic lost order

Viewed 64

I have a function that receives an array ([a,b]) as it's second argument. We don't know it's type, in the function, so we create a generic for that.

The array is passed though to a callback in that function.

When used in the callback later on, the array has lost its ordering type-wise. TypeScript thinks the array could be [b,a] as well as [a,b] because it's generic is (a|b)[] instead of [a,b].

It can be done with passing the type to the function to override the generic, but I would like to avoid that.

The two console.logs gives type errors. How can I make a generic that respects the ordering of the array?

The below code is run in TypeScript Playground.

function useOnChange<Dependencies extends Array<unknown>>(callback: (oldValue: Dependencies) => void, dependencies: Dependencies) {
    callback(dependencies);    
}

const a = { test: "something"}
const b = { test2: "else" }

useOnChange(([a,b]) => {
    // I array destruct the argument by their index in the array
    // Therefore a === a and b === b.
    // But TypeScript thinks the argument (which we destructed) is (a|b)[] and not [a,b].
    // In other words: It thinks it could be [b,a] as well as it could be [a,b]. It ignores the order of the array.

    console.log(a.test);
    console.log(b.test2);
}, [a,b])

// This works, but I believe it shouldve worked without
useOnChange<[{test: string}, {test2: string}]>(([a,b]) => {
    console.log(a.test);
    console.log(b.test2);
}, [a,b])
1 Answers
Related