【发布时间】:2020-03-27 14:44:29
【问题描述】:
TypeScript 拒绝编译 debounce 函数,因为包装函数的类型有问题:
export function debounce<F extends ((...args: any[]) => void)>(fn: F, timeout: number): F {
let timer: NodeJS.Timeout | undefined
// Problem here, TypeScript complains it's not the same function as F
return ((...args: any[]) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => fn(...args), timeout)
})
}
错误:
Type '(...args: any[]) => void' is not assignable to type 'F'.
'(...args: any[]) => void' is assignable to the constraint of type 'F', but 'F' could be instantiated with a different subtype of constraint '(...args: any[]) => void'.ts(2322)
如何解决这个问题?没有强制类型转换 return ... as F 或 return ... as any
【问题讨论】:
-
this answer 非常详细地介绍了此错误消息。看看你能不能用它解决你的问题。
标签: typescript