我定义了以下函数:
function someFunc<T extends any[]>(callback: (...args: T) => void, params: T) {}
但当我调用它时,TypeScrip的行为并不像我预期的那样:
// this works
// hovering over a, b, and c reveals that they're numbers
someFunc((a, b, c) => {}, [1, 2, 3]);
// this doesn't work
// hovering over a, b, and c reveals that they're of type `number | string`
someFunc((a, b, c) => {}, [1, '2', 3]);
我认为我的解决方案的问题在于,TypeScrip将someFunc
的第二个参数解释为数组而不是元组,因此结果类型要么是相同类型的数组,如number[]
,要么是联合类型(number | string)[]
的array.
如何确保每个参数的类型对应于参数元组中的相应类型?