如果我想为变量分配一个类型,稍后将像这样分配一个 setInterval:
this.autoSaveInterval = setInterval(function(){
if(this.car.id){
this.save();
}
else{
this.create();
}
}.bind(this), 50000);
应该为 this.autosaveInterval 变量分配什么类型?
晚会,但最好的类型(特别是因为类型是不透明的,我们只关心我们可以稍后将它传递给
clearInterval()
)可能是自动推导出的类型,即。像:
ReturnType<typeof setInterval>
类型为数字;
private autoSaveInterval: number = setInterval(() => {
console.log('123');
}, 5000);
我相信它的 NodeJS.Timeout 和 widow.setInterval 是数字:
const nodeInterval: NodeJS.Timeout = setInterval(() => {
// do something
}, 1000);
const windowInterval: number = window.setInterval(() => {
// do something
}, 1000);
尽管我能够运行该应用程序
id: number;
this.id = setInterval(...)
测试会通知您类型“超时”不可分配给类型“数字” 所以我采用了https://stackoverflow.com/a/59681620/18975994方法,这对我有用。
对于这样的东西,它被视为一个不透明的句柄,不值得为了满足 Windows 与节点环境而与类型作斗争。只需使用它并完成它:
let timerHandle: any = null;
function start() {
timerHandle = setInterval(...);
}
export function stop() {
if (timerHandle) clearInterval(timerHandle);
}
使用 typeof 运算符查找任何变量的数据类型,如下所示:
typeof 是放在单个操作数之前的一元运算符 可以是任何类型。它的值是一个字符串,指定 操作数的类型。
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 ))