在Angular 2+和Typescript中使用字符串作为变量名

6

在常规JavaScript中,我们可以使用字符串为名称向window全局对象添加属性,如下所示:

const str = "myVar";
window[str] = "Value";
console.log(myVar);

但是在Angular 2/4和Typescript中是否有一种方式可以完成类似的工作呢?我们可以使用this.myVar将常规变量存储在组件中,但是是否有一种方法可以使用字符串来创建相同的变量名称?例如:

const str = "myVar";
this[str] = "Value";
// the result should be the similar as this.myVar = "Value";

enter image description here

enter image description here


1
从技术上讲,这并不是“创建一个变量”,而是向window对象添加属性。 - Henry
@echonax,不,它根本不起作用:我看不到我的 console.log - P.S.
@CommercialSuicide https://stackblitz.com/edit/angular-aszgmk?file=app%2Fapp.component.ts - eko
@echonax,有点奇怪,因为我添加了这些行后不能直接编译项目。我已经更新了答案并附上了编译错误信息... - P.S.
@CommercialSuicide 啊,没错,它无法编译是因为 TypeScript 检查,但实际上它是合法的代码(这就是我想指出的)。 - eko
显示剩余5条评论
2个回答

10
您可以在您的类上允许动态属性:
class Test {
  [key: string]: any;

  constructor() {
    const str = "myVar";
    this[str] = "Value";
    console.log(this.myVar);
  }
}

但请确保您真的需要它,因为这会导致失去类型检查:

class Test {

  [key: string]: any;

  constructor() {
    this.teet(); // typo and therefore you will get an error in runtime
  }

  test() {

  }
}

9
我认为您可以使用以下方式访问,而Typescript接受这种语法。
this["myVar"] 

替换为

this.我的变量


这对我来说是一种意外的行为,但是没错,它可以工作!而且没有编译错误!那么 this["myVar"]this.myVar 是不同的吗?在我现在的理解中,它们应该是相同的... - P.S.
@CommercialSuicide 我认为这并不是回答问题,而只是以另一种方式使用 this[str]。你应该检查 yurzui 的回答。 - eko
@echonax,没错!yurzui的回答比我的好;) - notnotundefined
@CommercialSuicide 还有应该避免动态添加属性,因为这会破坏 TypeScript 的目的。 - notnotundefined
@Thabung,只有一次,当我需要将对象属性用作变量名时 ;) - P.S.
我必须说“避免它”。这是TypeScript。 - notnotundefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接