6

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

10
  • So did you try this and fail? Commented Sep 29, 2017 at 6:05
  • @echonax, yes, I did: TSLint gives me an error Commented Sep 29, 2017 at 6:05
  • 1
    Technically, this doesn't "create a variable" but add a property to the window object. Commented Sep 29, 2017 at 6:07
  • @Henry, yes, my explanation is not absolutely right, sorry Commented Sep 29, 2017 at 6:08
  • Henry is right, this will work but typescript will give the error in typechecking. I don't think there's a way to make it work like this. Commented Sep 29, 2017 at 6:08

2 Answers 2

10

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

  }
}
Sign up to request clarification or add additional context in comments.

Comments

9

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

this["myVar"] 

instead of

this.myVar

6 Comments

It's a little unexpected behavior for me, but yes, it works! And without compile errors! So are this["myVar"] and this.myVar different? In my understanding for now they should be the same...
@CommercialSuicide i don't think this answers the question, this is just using this[str] in another manner. You should check yurzui's answer.
@echonax, right! yurzui 's answer is better than mine ;)
@CommercialSuicide also dynamic addition of properties should be avoided as it defeats the purpose of Typescript
@Thabung, just one time, when I will need to use object properties as variable names ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.