ts函數(shù)中,直接使用this會報錯:
"this" 隱式具有類型 "any",因為它沒有類型注釋。
應(yīng)該以參數(shù)形式聲明this,以防抖函數(shù)為例
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);
};