TypeScript - what type is setInterval
Asked Answered
W

9

124

If I'd like to assign a type to a variable that will later be assigned a setInterval like so:

this.autoSaveInterval = setInterval(function(){
      if(this.car.id){
        this.save();
      }
      else{
        this.create();
      }
    }.bind(this), 50000);

What type should be assigned to this.autosaveInterval vairable?

Wongawonga answered 17/7, 2018 at 8:27 Comment(3)
public autoSaveInterval :number;Smell
You don't need to specify a type; autoSaveInterval will infer its type from the return value of the setInterval call. In browser platforms this is number, but in node.js it's a TimerDeface
Related github issue: github.com/microsoft/TypeScript/issues/842Guerin
I
252

Late to the party, but the best type (especially since the type is opaque, we only care that we can pass it to clearInterval() later) might be the automatically deduced one, ie. something like:

ReturnType<typeof setInterval>
Impudicity answered 10/1, 2020 at 12:23 Comment(6)
Man, this should definitely have been picked as the correct answer. "number" doesn't work, especially in angularTwylatwyman
I'm joining the party, number didn't work for me either, thank you!!Complect
Cleanest way of solving the problem, and works in all environmentsShiksa
Wow, didn't know about ReturnType. That's huge!Griefstricken
ChatGPT couldn't figure this one out, so thank you for this.Malicious
It should also be noted that according to the @types/node package, v16 setInterval returns NodeJS.Timer, while v18 setInterval returns NodeJS.Timeout. This answer's method is superior for migration concerns because using ReturnType will always be correct.Trimetric
F
125

The type depends on which function you are going to use there are 2 overloads, the return type is marked in red bounding-box :

enter image description here

In order to use the one which returns number, please use :

window.setInterval(...)
Fuddyduddy answered 14/3, 2019 at 8:11 Comment(4)
Could you share the website or book you got this reference?Thanks.Heliograph
Hi this is not a book you can find it if you working with visual studio and search for implementation .Fuddyduddy
In browsers environment, it should be window.setInterval and the return type is number as it is.Dative
Yes this worked for me and I set the type as let intervalId: number | undefined = undefined;Hippie
A
48

The type is number;

private autoSaveInterval: number = setInterval(() => {
  console.log('123');
}, 5000);
Acne answered 17/7, 2018 at 8:37 Comment(3)
@gfels Because setInterval return that representing the ID value of the timer that is set. You can use this value with the clearInterval() method to cancel the timer. It's not a function because you are not assigning the function handler to it, you are assigning the result/return value of a function to it.Acne
If you are using TypeScript, and you get compiler errors because somehow the NodeJS.Timer type is inferred: change to window.setInterval to specify you're not using node and the DOM type should be used, which is number indeed.Providential
It's not number in node.jsAntisana
S
27

I believe its NodeJS.Timeout and widow.setInterval is number:

const nodeInterval: NodeJS.Timeout = setInterval(() => {
  // do something
}, 1000);

const windowInterval: number = window.setInterval(() => {
  // do something
}, 1000);
Scofflaw answered 8/7, 2020 at 13:35 Comment(2)
The type it's not NodeJS.Timeout but NodeJS.TimerSorci
What is the NodeJs type? where it comes from?Began
M
3

As it's mentioned in other answers, the type of setInterval is either :number or :NodeJS.Timer.

I would like to extend the scope of the answer a little bit if anyone is looking to use setInterval with React and Typescript

const Clock: React.FC = () => {
  const secondsRef = useRef<NodeJS.Timer>();

  useEffect(() => {
    secondsRef.current = setInterval(() => { // type is taken correctly and no errors
      // do your stuff...
    }, 1000);
  }, []);

  return (
    <div>
      {/* your jsx... */}
    </div>
  );
};

export default Clock;

Hope someone will find my answer helpful... happy coding :)

Myasthenia answered 6/5, 2023 at 22:36 Comment(0)
S
2

For something like this, it is treated as an opaque handle, it isn't worth struggling with types just to satisfy the windows vs node environments. Just use this and be done with it:

let timerHandle: any = null;

function start() {
  timerHandle = setInterval(...);
}

export function stop() {
  if (timerHandle) clearInterval(timerHandle);
}
Soninlaw answered 16/4, 2023 at 12:46 Comment(0)
J
0

Although i was able to run the app with

id: number;

this.id = setInterval(...)

a test will inform you that Type 'Timeout' is not assignable to type 'number' so i went with https://mcmap.net/q/179865/-typescript-what-type-is-setinterval approach, that worked for me.

Juice answered 8/2, 2023 at 10:34 Comment(0)
C
0

This is the type for setInterval: NodeJS.Timer

Capwell answered 18/7, 2023 at 9:30 Comment(0)
L
-2

Use typeof operator to find data type of any variable like this:

typeof is an unary operator that is placed before a single operand which can be of any type. Its value is a string that specifies the type of operand.

var variable1 = "Hello";
var autoSaveInterval;

this.autoSaveInterval = setInterval(function(){
      if(this.car.id){
        this.save();
      }
      else{
        this.create();
      }
    }.bind(this), 50000);
    
console.log("1st: " + typeof(variable1))
console.log("2nd: " + typeof(autoSaveInterval ))
Luzern answered 17/7, 2018 at 8:35 Comment(2)
This is not helping with Typescript definitionsOogonium
This does not contain any reference to the original question regarding TypeScript typesHydrogenous

© 2022 - 2024 — McMap. All rights reserved.