TypeScript - what type is setInterval

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?

90628 次浏览

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

The type is number;

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

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

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>

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