【发布时间】:2018-08-07 18:46:57
【问题描述】:
我正在用 TypeScript 编写一个应用程序,我正在使用 Rollup 将文件捆绑在一起,并使用 Buble / Babel 将编译后的 Javascript 转换为浏览器可以使用的东西。然而,当我运行rollup -c 时,我得到一个错误:
semantic error TS2495 Type 'Radius' is not an array type or a string type.
不知道该怎么做,因为我可以通过正常的搜索引擎路径找到关于 TypeScript 中迭代器的信息似乎并不多。这是我的文件:
rollup.config.ts
import typescript from 'rollup-plugin-typescript2';
import uglify from 'rollup-plugin-uglify';
import buble from 'rollup-plugin-buble';
export default {
input: "./chess-player.ts",
output: {
file: "./chess-player.min.js",
format: "iife"
},
watch: {
include: [
"./chess-player.ts",
"./src/*/*.ts",
"./src/*.ts"
]
},
plugins: [
typescript(),
buble(),
uglify()
]
};
tsconfig.json:
{
"compilerOptions": {
"target": "ES2015",
"module": "ES2015",
"strict": true,
"removeComments": true,
"esModuleInterop": true
}
}
radius.ts:
export class Radius implements IterableIterator<number> {
counter: number;
max?: number;
[Symbol.iterator](): IterableIterator<number> {
return this;
}
next(): IteratorResult<number> {
if (!this.max || this.counter < this.max) {
this.counter++;
return {
value: this.counter,
done: false
};
} else {
this.counter = 0;
return {
value: undefined,
done: true
};
}
}
constructor(max?: number) {
this.counter = 0;
this.max = max;
}
}
Radius 的实例作为Piece 类的属性实现。这是尝试使用它的方法:
checkAttackRadius(boardElement: HTMLElement, pieceSquare: Square): void {
const piece = pieceSquare.piece;
let vectors = piece.attacks();
for (let radius of piece.radius) {
const remaining = this.remaining(vectors);
if (radius > 14 || remaining === 0) {
break;
}
for (let j = 0; j < vectors.length; j++) {
this.checkAttackVector(boardElement, pieceSquare, vectors[j], radius);
}
}
}
【问题讨论】:
-
您确定您的编译器设置吗?我认为它们是不正确的,因为 a)
strict在您return { value: undefined, done: true };时会导致错误 b) 您遇到的错误是 es5 编译目标的典型错误 -
@Titian Cernicova-Dragomir 不,我不确定我的编译器设置!除了将
target和module设置为ES2015以便我可以使用迭代器并且输出与Rollup 兼容之外,我对设置什么并只使用默认值一无所知。但是,我只是尝试删除"strict": true,并再次运行rollup -c,但得到了相同的结果。 -
@Tao 如果我错了,请纠正我。 a) 我正在编译到 ES2015,所以我不需要使用
downlevelIteration标志。 b)我正在编译到 ES2015,然后使用 Babel,所以看起来我需要使用 polyfill。好的,完成了,但得到了相同的结果。 c) 手动调用 next() 似乎毫无意义,因为它破坏了迭代器的要点。 -
@Aaron,对不起,我想我应该说“也许这有帮助”而不是“看到这个问题”。我记得不久前看到了一个类似的问题,并认为它可能会对您有所帮助。我怀疑汇总是罪魁祸首。只有 ts 我只得到 Titian 提到的错误。
标签: typescript iterator rollupjs