Attempting to create a custom iterable in my Angular application has resulted in an error message: "Type 'Connection' is not an array type or a string type." This occurs when trying to loop through the class using a for..of statement.
Further investigation revealed that this error can occur in ES5 when attempting to iterate through anything other than an array [] or a string using for..of. I believed that as TypeScript is a superset of ES6, which compiles down to ES5 as defined in tsconfig.json, I should be able to use this technique. Is my understanding incorrect?
Data Transfer Object (DTO):
export class Property{
key: string;
value: any;
}
Iterator:
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;
}
Iterable:
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);
}
}
Usage example where the error occurs, with 'this.connection' being highlighted:
getData(): Property[] {
let info: Property[] = []
for(let value of this.connection){
info.push(value)
}
TypeScript Version: 2.7.2