Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 830
Commercial Suicide Avatar asked Sep 29 '17 06:09

Commercial Suicide


2 Answers

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

this["myVar"] 

instead of

this.myVar

like image 178
notnotundefined Avatar answered Oct 18 '22 17:10

notnotundefined


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() {

  }
}
like image 27
yurzui Avatar answered Oct 18 '22 18:10

yurzui