简体   繁体   English

如何在 TypeScript / JavaScript 中定义多个命名属性

[英]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.

相关问题 如何在 TypeScript 中的类型上定义互斥属性? - How to define mutually exclusive properties on a type in TypeScript? 如何根据 JavaScript/Typescript 中的多个属性过滤对象数组? - How to filter an array of objects based on multiple properties in JavaScript/Typescript? 如何在JavaScript中定义属性子类 - How to define properties subclasses in javascript 如何创建动态命名的JavaScript对象属性? - How to create dynamically named JavaScript object properties? JavaScript-如何在对象定义中定义属性 - JavaScript - How to define Properties in Object Definition TypeScript:在代理中定义动态属性 - TypeScript: define dynamic properties in proxy 如何定义 Object 类型,其中包含 Typescript 中的数字属性 - How to Define Object type that contains properties as number in Typescript 如何访问 LoadAssets 中 AssetLoadedFunc 的属性? 打字稿? Javascript? - How to access properties of AssetLoadedFunc in LoadAssets? TypeScript? Javascript? 在 Async/Await JavaScript(或更好的 TypeScript)中展平一组具有命名属性的未知深层对象 - Flatten an array of unknown deep objects, with named properties, in Async/Await JavaScript (or better TypeScript) 如何在 Javascript 中设置多个属性 - How to set multiple properties in Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM