我有一个接收数组 ([a,b]) 作为第二个参数的函数。我们不知道它在函数中的类型,因此我们为此创建了一个泛型。
数组被传递给该函数中的回调。
稍后在回调中使用时,数组已失去其类型顺序。 TypeScript 认为数组可以是 [b,a] 和 [a,b],因为它的泛型是 (a|b)[] 而不是 [a,b]。
可以通过将类型传递给函数来覆盖泛型来完成,但我想避免这种情况。
两个 console.logs 给出类型错误。我如何制作一个遵循数组顺序的泛型?
以下代码在 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])
最佳答案
一般休息应该可以解决问题。解释于:https://medium.com/javascript-in-plain-english/typescript-generic-rest-parameters-and-tuple-types-in-practice-edc2bb0bdcb9
function useOnChange<T extends unknown[]>(callback: (oldValue: [...T]) => void, dependencies: [...T]) {
callback(dependencies);
}
const a = { test: "something"}
const b = { test2: "else" }
useOnChange(([a,b]) => {
console.log(a.test);
console.log(b.test2);
}, [a,b])
关于TypeScript 数组泛型丢失顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65613262/