TypeScript 中的 setTimeout 应该使用什么返回类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51040703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:29:59  来源:igfitidea点击:

What return type should be used for setTimeout in TypeScript?

typescript

提问by Harshal Patil

Consider following code:

考虑以下代码:

const timer: number = setTimeout(() => '', 1000);

Typescript throws an error: Type 'Timer' is not assignable to type 'number'.Quick lookup tells me that setTimeoutreturns NodeJS.Timer.

打字稿引发错误:Type 'Timer' is not assignable to type 'number'.快速查找告诉我setTimeout返回NodeJS.Timer.

But if I am doing browser-based development, using NodeJS.Timerfeels wrong. Which is the correct type definition or return type for making setTimeoutwork without resorting to anydeclaration?

但是如果我在做基于浏览器的开发,使用NodeJS.Timer感觉不对。哪个是在setTimeout不诉诸any声明的情况下进行工作的正确类型定义或返回类型?

回答by Titian Cernicova-Dragomir

Simplest solution is to allow type inference to work and not specify any type at all. If you need to specify a type, seeing as the type is not consistent between the browser and node declarations, you could use ReturnTypeto specify that the type of the variable is whatever the return type of setTimeoutis:

最简单的解决方案是允许类型推断工作并且根本不指定任何类型。如果你需要指定一个类型,因为浏览器和节点声明的类型不一致,你可以使用ReturnType指定变量的类型setTimeout是返回类型是什么:

const timer: ReturnType<typeof setTimeout> = setTimeout(() => '', 1000);

Alternately, window.setTimeoutcan also be used instead of just setTimeout. It returns proper return type.

或者,window.setTimeout也可以使用而不仅仅是setTimeout. 它返回正确的返回类型。

回答by Andrii Verbytskyi

You can use window.setTimeoutit returns a type of number.

您可以使用window.setTimeout它返回一个类型的number.

let a: number;
a = window.setTimeout(function() {}, 0);

回答by Dmitry

window.setTimeoutreturns number. Ideally, you want to define your own type to distinguish it from number (and prevent some ops like +which don't make sense for timers).

window.setTimeout返回number。理想情况下,您希望定义自己的类型以将其与数字区分开来(并防止一些+对计时器没有意义的操作)。

type TimerHandle = number;

回答by Yotam707

For anyone else having this error what worked for me is adding in the tsconfig.js file:

对于遇到此错误的其他任何人,对我有用的是在 tsconfig.js 文件中添加:

"compilerOptions": {

   ...
   "types": [],
}