【问题标题】:Typescript const reusing property values to define new propertiesTypescript const 重用属性值来定义新属性
【发布时间】:2016-11-10 00:25:18
【问题描述】:

有没有一种方法可以重用 Typescript 中 const 对象中定义的属性值来定义同一对象中的其他新属性?

类似这样的:

const TEST = {
  "a1": "world",
  "a2": "hello",
  "a3": this.a1
};

console.log(TEST.a3);立即记录未定义的日志。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    没有,因为那时还没有定义 TEST
    例如,如果您尝试这样做:

    const TEST = {
      "a1": "world",
      "a2": "hello",
      "a3": TEST["a3"]
    };
    

    你会得到:

    错误:在声明之前使用了块范围变量“TEST”

    你可以这样做:

    const TEST = {
      "a1": "world",
      "a2": "hello"
    } as { a1: string, a2: string, a3: string };
    
    TEST.a3 = TEST.a1;
    

    (code in playground)

    【讨论】:

      猜你喜欢
      • 2012-02-15
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2019-07-19
      相关资源
      最近更新 更多