简体   繁体   English

Angular2 动态访问这个对象打字稿

[英]Angular2 dynamically access this object typescript

In an Angular2 typescript component I have the following local variables在 Angular2 打字稿组件中,我有以下局部变量

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.所以在这个例子中,我传递了局部变量“teapot20”的字符串名称,我想用这个字符串来操作名为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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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