ts函数中,直接使用this会报错:
"this" 隐式具有类型 "any",因为它没有类型注释。
应该以参数形式声明this,以防抖函数为例
function debounce(fn: Function, time: number) {
let timer: number
return function(this: object, ...args: any[]) {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
clearTimeout(timer)
}, time)
}
}
编译后得到的js:
"use strict";
function debounce(fn, time) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
clearTimeout(timer);
}, time);
};