TypeScript - f.e 是什么类型。设置间隔

TypeScript - what type is f.e. setInterval

如果我想为变量分配一个类型,稍后将像这样分配一个 setInterval:

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

应该为 this.autosaveInterval 变量分配什么类型?

使用 typeof 运算符查找任何变量的数据类型,如下所示:

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

类型为数字;

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

类型取决于您要使用的函数有 2 个重载,return 类型用红色边界框标记:

为了使用return的号码,请使用:

window.setInterval(...)

迟到了,但最好的类型(特别是因为类型是不透明的,我们只关心我们可以稍后将它传递给 clearInterval())可能是自动推导的类型,即。类似于:

ReturnType<typeof setInterval>

我相信它的 NodeJS.Timeout 和 widow.setInterval 是数字:

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

const windowInterval: number = window.setInterval(() => {
  // do something
}, 1000);