Typescript 中 setTimeout() 的返回类型
What’s the Return Type for setTimeout() in Typescript
使用ReturnType
实用程序类型获取setTimeout
方法的返回类型,例如const timeout: ReturnType<typeof setTimeout> = setTimeout()
。ReturnType
实用程序类型构造一个由函数的返回类型组成的类型。
索引.ts
const timeout: ReturnType<typeof setTimeout> = setTimeout(() => { console.log('success'); }, 1500); console.log(timeout);
ReturnType
实用程序类型允许我们构造一个由传入函数的返回类型组成的类型。
索引.ts
function sum(a: number, b: number) { return a + b; } // 👇️ type T = number type T = ReturnType<typeof sum>;
需要这种方法,因为
setTimeout方法的返回类型NodeJS.Timeout
在 Node 和number
浏览器中。
By using the
ReturnType
utility type we are able to get the correct return type of the setTimeout
method regardless if writing code server or client side.It should be noted that even though the return type of the setTimeout
method
is different between Node.js and the browser, the return value is used in the
same way – it is passed to the clearTimeout()
method to cancel the timeout if
necessary.
index.ts
const timeout: ReturnType<typeof setTimeout> = setTimeout(() => { console.log('success'); }, 1500); clearTimeout(timeout);
The clearTimeout
method takes a number
or a NodeJS.Timeout
object as a
parameter (depending on the environment), so you can directly pass the timeout
value to the method.