What return type should be used for setTimeout in TypeScript?

What return type should be used for setTimeout in TypeScript?

Consider the following code:

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

TypeScript throws an error: Type ‘Timer’ is not assignable to type ‘number’. A quick lookup suggests that setTimeout returns NodeJS.Timer.

However, if I am working in a browser environment using NodeJS.Timer seems inappropriate. What is the correct type definition or return type for setTimeout in TypeScript without resorting to using any?

Hey there,

i would love to share my point here with you hope this helps:

Use ReturnType<typeof setTimeout> In a browser environment, setTimeout returns a different type compared to Node.js.

You can use TypeScript’s ReturnType utility type to infer the correct return type based on the environment. This ensures you get the right type, whether you’re working in a browser or Node.js.

Example:

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

In the browser, setTimeout returns a number, so you can safely type the return value as number. This is appropriate for browser environments and ensures TypeScript doesn’t throw an error.

Example: const timer: number = setTimeout(() => '', 100

Hope this helps :slight_smile:

My solution here is you can use NodeJS.Timeout in Node.js Environment

If you’re working in a Node.js environment and need a specific type, use NodeJS.Timeout instead of number. You can import NodeJS.Timeout from the @types/node package for Node.js-based projects.

Example (Node.js):


const timer: NodeJS.Timeout = setTimeout(() => '', 1000);