-1

Dynamically access object property using variable but with angular2/typescript is possible?

Community
  • 1
  • 1
Progs
  • 1,059
  • 7
  • 27
  • 63

2 Answers2

1

Yes, Typescript is a superset of javascript. So, if you can do it in javascript, you can (almost always) do it in Typescript verbatim.

For your specific example, the same answer given to the question above will work.

snorkpete
  • 14,278
  • 3
  • 40
  • 57
0

Angular2 seems to have nothing to it.

Just as Snorkpete already managed to say: with TS yes and it looks alike. Just to illustrate it:

Based on winning answer from question which you pointed at:

class Barf {
    private bar:boolean = false;

    public foo(): any {
        let propName = 'bar'; // can be const as well
        return this[propName];
    }
}

when pushed through es5 grinder tsc --target es5 Barf.ts gives:

var Barf = (function () {
    function Barf() {
        this.bar = false;
    }
    Barf.prototype.foo = function () {
        var propName = 'bar';
        return this[propName];
    };
    return Barf;
}());

and when pushed through es6 grinder tsc --target es6 Barf.ts gives:

class Barf {
    constructor() {
        this.bar = false;
    }
    foo() {
        let propName = 'bar';
        return this[propName];
    }
}
Community
  • 1
  • 1
gaa
  • 1,132
  • 11
  • 26