如何在TypeScript中的Input onChange事件中使用debounce



这就是我使用Debounce 的地方

const handleSearch = debounce((value: string) => {
const filter = tableDataCopy.filter(
(item) => item[condition].toLowerCase().indexOf(value) !== -1,
);
setTableData(filter);
}, 500);

onChange事件:

onChange={(e: ChangeEvent<HTMLInputElement>) => handleSearch(e.target.value)}

防反弹功能:

export function debounce(func: Function, delay: number) {
let timer: NodeJS.Timeout | null = null;
return function (this: any) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.call(this, ...arguments);
}, delay);
};
}

我在打字脚本中得到一个参数错误:

TS2554: Expected 0 arguments, but got 1.

我知道这是错误的,但我不知道如何通过Debounce 中的论点

首先,this是一个特殊的函数参数。它指定函数中所需的上下文类型(this(。这算不上真正的争论。这意味着function (this: any) {}是一个参数为零的函数。


其次,never在typescript中使用arguments关键字。由于各种原因,它可能很棘手(它不是一个真正的数组,也不能键入(。相反,接受映射到变量的一系列参数。

类似:

function (...args: string[]) {}

第三,Typescript需要知道从debounce返回的函数类型。Function不够好。它需要知道debounced函数接受的参数。为此,您必须使用泛型类型参数。

这变得有点复杂。

function debounce<
T extends unknown[]
>(
func: (...args: T) => void,
delay: number,
):
(...args: T) => void
{
let timer: number | null = null;
return (...args: T) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.call(null, ...args);
}, delay);
};
}

这是通用参数:

T extends unknown[]

并将其用作func参数类型:

func: (...args: T) => void

并且在函数的返回类型中:

: (...args: T) => void

现在,传递给debounce的函数将由泛型参数注意到其参数,并且返回的函数将具有完全相同的参数。


最后,您不需要在onChange中指定事件类型。React知道元素的类型,所以typescript可以知道参数的类型。

<input type="text" onChange={e => handleSearch(e.target.value)} />

TypeScript操场上的工作示例

最新更新