以下代码在编译目标为ES5时进行编译,但是在切换到ES6或ES2016或ES2015时会产生编译错误。
type Grid<T> = {
cells: T[]
}
type Cell = {
position: number;
}
type UI_Cell = Cell & {
thingy: number;
}
type Battle = {
grid: Grid<Cell>
}
type UI_Battle = Battle & {
grid: Grid<UI_Cell>
}
let battle: UI_Battle;
function mami() {
for (const cell of battle.grid.cells) {
console.log(cell.thingy); // Error: Property 'thingy' does not exist on type 'Cell'
}
}
可以通过明确地执行以下操作来修复错误:
const cells: UI_Cell[] = battle.grid.cells;
for (const cell of cells) {
console.log(cell.thingy);
}
但这很不方便,只是“怪异”。是编译器错误吗?