我正在尝试在我的角度应用程序中实现自定义迭代。我收到此错误:“类型'连接'不是数组类型或字符串类型。” 当我尝试使用 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