Typescript如何将数组值转换为类变量

时间:2017-01-26 10:21:16

标签: angular typescript

假设密钥是' abc'和价值' true',我应该能够访问' this.abc&#39 ;;这应该归还我的

Class A {
    public someFun(){
        this.external.getData().subscribe((externalStream: Array<someType>) => {
            for(let i:number = 0; i < externalStream.length; i++){
                console.info(externalStream[i].key);    // This should be class variable
                console.info(externalStream[i].value);  // This should be above variable's value

            }
        })
    }
}

2 个答案:

答案 0 :(得分:2)

试试这个:

Class A {
    public someFun(){

        const obj = this;

        this.external.getData().subscribe((externalStream: Array<someType>) => {
            for(let i:number = 0; i < externalStream.length; i++){
                obj[externalStream[i].key] = externalStream[i].value;
            }
        })
    }
}

答案 1 :(得分:0)

Typescript允许您创建字典类型(有时也称为哈希映射)。这是由于Typescript中的类型安全特性,这种JavaScript代码是不可能的:

var value = {};
value.abc = true;
for (var key in value) {
    console.info(key);
    console.info(value[key]);
}

对于类型安全的方法,您需要在编译时知道abc属性的存在,而您通常不会这样做。所以你用字典类型做到这一点:

let value: { [key: string]: boolean };
value['abc'] = true;
for (var key in value) {
    console.info(key);
    console.info(value[key]);
}

在你的情况下:

class A {
    public someFun(){
        this.external.getData().subscribe((externalStream: Array<{ [key: string]: boolean }>) => {
            for(let i:number = 0; i < externalStream.length; i++){
                for(let key in externalStream[i])  {
                    console.info(key);
                    console.info(externalStream[i][key]);
                }
            }
        })
    }
}