2

In an Angular2 typescript component I have the following local variables

teapot10: boolean = false;
teapot20: boolean = false;
teapot30: boolean = false;

I want to use these dynamically in a function like so

doSomeStuff("teapot20")

doSomeStuff(teapot: string){
    this[teapot] = true
}

So in this example I pass the string name of the local variable "teapot20" and I want to use this string to manipulate the actual variable called teapot20.

Can I do this?

Thanks

4
  • 4
    Remove the dot, should be: this[teapot] Commented Jan 23, 2017 at 14:55
  • Do you mean this[teapot] ? Commented Jan 23, 2017 at 14:55
  • thats a typo... thats what i used but doesn't work Commented Jan 23, 2017 at 14:58
  • it does work!! I was using the wrong variable in my code... arse Commented Jan 23, 2017 at 15:02

1 Answer 1

1

You better use string literals instead of just a string:

doSomeStuff(teapot: "teapot10" | "teapot20" | "teapot30") {
    this[teapot] = true
}

Or:

type PropNames = "teapot10" | "teapot20" | "teapot30";
doSomeStuff(teapot: PropNames) {
    this[teapot] = true
}

This way you can make sure that no one calls it like so:

doSomeStuff("tepo10");
Sign up to request clarification or add additional context in comments.

Comments

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.