我在编译这段特定代码时遇到问题(这是来自 Angular2 项目)。
public reloadRecords() {
let step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps;
let data = new Array(this.recordsChartSteps);
let labels = new Array(this.recordsChartSteps);
let doneCount = 0;
let done = new EventEmitter();
done.subscribe(() => {
this.recordsChartData[0].data = data;
this.recordsChartLabels = labels;
});
if (this.timeInterval.min == 0)
this.data.getRecordCount(this.timeInterval.min, this.timeInterval.max).subscribe(count => {
data[data.length - 1] = count;
labels[labels.length - 1] = "Total";
done.emit();
});
else for (let i = 0; i < this.recordsChartSteps; i++) {
let min = this.timeInterval.min + step * i;
let max = min + step - 1;
this.data.getRecordCount(min, max)
.subscribe(count => {
data[i] = count;
labels[i] = "De " + new Date(min).toLocaleTimeString() + " à " + new Date(max).toLocaleTimeString();
if (++doneCount >= this.recordsChartSteps) done.emit();
});
}
}
使用 typescript 版本 2.0.10(来自 npm),这是我得到的输出。
GlobalViewComponent.prototype.reloadRecords = function () {
var _this = this;
var step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps;
var data = new Array(this.recordsChartSteps);
var labels = new Array(this.recordsChartSteps);
var doneCount = 0;
var done = new core_1.EventEmitter();
done.subscribe(function () {
_this.recordsChartData[0].data = data;
_this.recordsChartLabels = labels;
});
if (this.timeInterval.min == 0)
this.data.getRecordCount(this.timeInterval.min, this.timeInterval.max).subscribe(function (count) {
data[data.length - 1] = count;
labels[labels.length - 1] = "Total";
done.emit();
});
else
var _loop_1 = function(i) {
var min = this_1.timeInterval.min + step * i;
var max = min + step - 1;
this_1.data.getRecordCount(min, max)
.subscribe(function (count) {
data[i] = count;
labels[i] = "De " + new Date(min).toLocaleTimeString() + " à " + new Date(max).toLocaleTimeString();
if (++doneCount >= _this.recordsChartSteps)
done.emit();
});
};
var this_1 = this;
for (var i = 0; i < this.recordsChartSteps; i++) {
_loop_1(i);
}
};
这是有效的 Javascript 代码,但编译器似乎没有为 else block 的内容添加必要的括号。
我知道这很可能是因为我没有在我的 Typescript 代码中添加这些括号,因为 else 语句包含一个 block (使括号不必要,如果我错了请纠正我)。
但是,在 Javascript 中,else block (Typescript 中的单个 for 循环)输出到多个语句。
您甚至可以看到缩进,我认为在第一个声明 _loop_1 变量的指令之后的两个指令也应该包含在这个 else block 中是有道理的。
我显然可以通过在我的 Typescript 代码中添加方括号来解决这个问题(据我所知,这可能是更好的做法)。
没有放置这些括号是我的错误,还是我应该报告编译器的问题?
注意:英语不是我的主要语言。
最佳答案
是的,这看起来像一个错误,您应该报告它。这是一个快速简化的复制:
var test = false;
if (test) for (let i = 0; i < 10; i++) {
let x = () => i;
}
该代码绝对应该什么也不做,如果您在我的本地 Chrome 中运行未编译的代码,它就会这样做。如果您通过 TypeScript 运行它,它会抛出“Uncaught TypeError: _loop_1 is not a function”。伟大的发现!
关于 typescript 编译器忘记添加括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886536/