简体   繁体   中英

Angular2 dynamically access this object typescript

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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM