P.S.
P.S.

Reputation: 16384

Use string as variable name in Angular 2+ and Typescript

In regular JavaScript we can add a property to window global object with name from string, like this:

const str = "myVar";
window[str] = "Value";
console.log(myVar);

But is there a way to do the similar job in Angular 2/4 and Typescript? We can store regular variables in component using this.myVar, but is there a way to create the same variable using string for the variable name? Something like:

const str = "myVar";
this[str] = "Value";
// the result should be the similar as this.myVar = "Value";

enter image description here

enter image description here

Upvotes: 6

Views: 21874

Answers (2)

yurzui
yurzui

Reputation: 214017

You can allow dynamic properties on your class:

class Test {
  [key: string]: any;

  constructor() {
    const str = "myVar";
    this[str] = "Value";
    console.log(this.myVar);
  }
}

But make sure you really need it because you're loosing typechecking with it:

class Test {

  [key: string]: any;

  constructor() {
    this.teet(); // typo and therefore you will get an error in runtime
  }

  test() {

  }
}

Upvotes: 10

notnotundefined
notnotundefined

Reputation: 3751

I think you can access using the following & Typescript accepts this syntax

this["myVar"] 

instead of

this.myVar

Upvotes: 9

Related Questions