[英]what type should timeout be defined at in typescript
我正在嘗試在打字稿中編寫一個 debounce 函數,但不確定要設置分配給setTimeout
的變量的類型。 我的代碼如下所示:
function debounced(func: () => void, wait: number) {
// what type should timeout be here?
let timeout: any;
return () => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func();
}, wait);
};
}
如果你希望你的代碼在 node.js 和瀏覽器環境之間是可移植的,你可以像這樣使用setTimeout
的返回類型:
let timeout: ReturnType<typeof setTimeout>;
因為它被聲明為在節點和瀏覽器中返回不同的類型。
Typescript 將自定義類型定義優先於默認類型。
如果您的 tsconfig.json 文件包含types: node
,它會告訴 Typescript 使用setTimeout(): NodeJS.Timeout
在node_modules/@types/node 中找到,而不是默認的setTimeout(): number
方法。
"compilerOptions": {
"types": [
"node",
...
]
}
如果您不明確需要該類型選項,請將其刪除,此錯誤將消失:
"compilerOptions": {
}
如果您只是使用瀏覽器,顯式調用window.setTimeout
應該可以解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.