Typescript常量重复使用属性值来定义新属性

问题描述:

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

像这样:

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

的console.log(TEST.a3);日志现在未定义。

不,因为TEST尚未定义。
例如,如果你试试这个:

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

您将获得:

Error: Block-scoped variable 'TEST' used before its declaration

你可以这样做:

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

TEST.a3 = TEST.a1; 

code in playground

+0

非常感谢为您的回应! – takeradi