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

前端 未结 3 772
遥遥无期
遥遥无期 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:39
    const btn: {[keys: string]: string} = {
        key: 'value',
        anotherKey: 'anotherValue'
    }
    

    This example should help you.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-01-29 04:54

    You can do it like following:

    config: { [key:string]: ButtonConfig } = {};
    
    ...
    this.config.submitButton = new ButtonConfig(...);
    ...
    

    Here's a working stackblitz project: https://stackblitz.com/edit/angular-opc8yg

    0 讨论(0)
提交回复
热议问题