角度のあるアプリにカスタム iterable を実装しようとしています。「Type 'Connection' is not an array type or a string type.」というエラーが表示されます。for..of を使用してクラスを繰り返し処理しようとすると
このfor..ofテクニックを使用して、[]または文字列以外のものを反復しようとすると、ES5でこのエラーが発生することがわかりました。TSはES6のスーパーセットであり、tsconfig.jsonで定義されたターゲットES5にコンパイルされるため、これを行うことができるはずだという私の理解は間違っていますか?
DTO:
export class Property{
key: string;
value: any;
}
イテレータ:
import { Property } from './dto/property';
export class PropertyIterator {
data: Property[] = [];
index: number = 0;
constructor(object: Object) {
Object.entries(object).forEach(
([key, value]) => {
this.data.push({ key, value })
}
);
}
next() {
var result = { value: undefined, done: false }
if (this.index < this.data.length) {
result.value = this.data[this.index++];
} else {
result.done = true;
this.index = 0;
}
return result;
}
反復可能:
import { PropertyIterator } from './../../property-iterator';
import { ConnectionBuilder } from './connection-builder';
import { Property } from '../property';
export class Connection implements Iterable<Property> {
connectionId: number; //required
type: string; //required
username: string; //required
password: string; //required
path: string; //required
serverName: string; //optional
port: number; //optional
constructor(builder: ConnectionBuilder){
this.connectionId = builder.ConnectionId;
this.type = builder.Type;
this.username = builder.Username;
this.password = builder.Password;
this.path = builder.Path;
this.serverName = builder.ServerName;
this.port = builder.Port;
}
[Symbol.iterator](){
return new PropertyIterator(this);
}
}
使用法、ここでエラーが発生します。this.connection には下線が引かれています。
getData(): Property[] {
let info: Property[] = []
for(let value of this.connection){
info.push(value)
}
TSC バージョン 2.7.2