How to declare an object whose properties are of type string only using TypeScript?

前端 未结 3 811
遥遥无期
遥遥无期 2021-01-29 04:21

I have a configuration array in my component like this.

...
config: ButtonConfig[];
...
this.config.push(new ButtonConfig(...));
...

Today, I r

3条回答
  •  無奈伤痛
    2021-01-29 04:43

    The most simple answer is this:

    export type ButtonConfigs = {
      [key: string]: ButtonConfig;
    }
    

    This works very well, if you want a high level of dynamics.

    If you want to lock it down a little, you could define an enum that contains the possible keys you want to allow:

    export enum ButtonConfigKeys {
      'submitConfig',
      'someOtherKey',
      '...'
    }
    
    export type ButtonConfigs = {
      [key: ButtonConfigKeys]: ButtonConfig;
    }
    

提交回复
热议问题