[英]How to define multiple named properties in TypeScript / JavaScript
In the 'sorting' property of the 'myItemA' object I would like to allow the definition of multiple flexibly named properties such as 'viewOrder', 'execOrder', 'persistOrder'... and use like this:在“myItemA”object 的“排序”属性中,我想允许定义多个灵活命名的属性,例如“viewOrder”、“execOrder”、“persistOrder”......并像这样使用:
myItemA.sorting.viewOrder = 3;
myItemA.sorting.execOrder = 7;
etc.
I am trying the definition of ItemA and the property sorting like this:我正在尝试ItemA的定义和属性排序,如下所示:
export abstract class ItemA {
constructor(
public id: string,
public name: string,
// (this is may not be correct - how to correct it ?)
public sorting?: [ {[name: string]: number} ],
...
and then create objects like this:然后像这样创建对象:
export const myItemA: ItemA =
{
id: 'A1',
name: 'A1',
// (compiler complains here - how to correct it ?)
sorting: [ {'viewOrder': 0}, {'execOrder': 0}, {etc.} ],
...
}
The syntax should be like this in the constructor:构造函数中的语法应该是这样的:
public sorting?: { [name: string]: number }
Or:或者:
public sorting?: Record<string, number>
And like this when declaring the variable:在声明变量时就像这样:
export const myItemA: ItemA = {
...
sorting: { 'viewOrder': 0, 'execOrder': 0 },
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.