TypeScript - what type is f.e. setInterval

JavascriptAngularTypescripttypescript2.0

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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(...)

Solution 3 - Javascript

The type is number;

private autoSaveInterval: number = setInterval(() => {
  console.log('123');
}, 5000);

Solution 4 - Javascript

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);

Solution 5 - Javascript

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 ))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongfelsView Question on Stackoverflow
Solution 1 - JavascriptJoachim Berdal HagaView Answer on Stackoverflow
Solution 2 - JavascriptStav BodikView Answer on Stackoverflow
Solution 3 - Javascriptuser3003238View Answer on Stackoverflow
Solution 4 - JavascriptAngularBoyView Answer on Stackoverflow
Solution 5 - JavascriptAshView Answer on Stackoverflow