0

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

4

1 回答 1

0

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

{
  "compilerOptions": {
    "downlevelIteration": true
    ...
  }
}
于 2018-03-27T22:15:27.340 回答