TS - 自定义可迭代 - 用于......错误

时间:2018-03-27 14:22:04

标签: angular typescript iterator for-of-loop

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

1 个答案:

答案 0 :(得分:0)

虽然阵列解决方法可行,但还有另一个更通用的解决方案。从版本2.3开始,TS实际上支持ES3 / 5目标的ES2015迭代器,但默认情况下禁用此支持。您可以通过在tsconfig.json文件中添加以下行来启用它:

{
  "compilerOptions": {
    "downlevelIteration": true
    ...
  }
}