【问题标题】:How to declare an object whose properties are of type string only using TypeScript?如何仅使用 TypeScript 声明其属性为字符串类型的对象?
【发布时间】:2020-01-07 07:36:15
【问题描述】:

我的组件中有一个这样的配置数组。

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

今天,我意识到让数组表现得像字典更有意义,这样我就可以不通过数字索引而是通过名称来访问特定元素。我希望能够做到config.submitButton 而不是config[3](即使我声明了一个将 submitButton 映射到请求索引的枚举)。

...
config = { };
...
this.config.submitButton = new ButtonConfig(...);
...

这可行,但我现在允许一堆any 欺骗我的代码库,这很糟糕。我希望对象知道只能将 ButtonConfig 类型的东西放入其中。

我可以用字段声明一个类,因为我希望它们的数量在将来可以动态添加,所以下面不会这样做。

export class ButtonConfigs {
  submitConfig: ButtonConfig, ...
}

我检查了the docssome examples 并没有真正意识到我在寻找什么。有可能还是我自己搞糊涂了?

【问题讨论】:

    标签: angular typescript types


    【解决方案1】:

    最简单的答案是这样的:

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

    如果您想要高水平的动态,这非常有效。

    如果你想稍微锁定它,你可以定义一个包含你想要允许的可能键的枚举:

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

    【讨论】:

    • 完美回复。接受为正确答案。并且 +1 用于完全不请自来的额外信息,实际上解决了我很快就会遇到的另一个问题。狙击手技能不错,伙计。
    • 你是说你的方法在使用接口之前是首选的吗?
    • 您的意思是使用type 而不是interface?我认为这是个人喜好。我的团队同意使用 type 而不是 interface 仅仅是因为单词的语义。
    • @知道了,谢谢。我很好奇,couldn't resist 在单独的线程中将其书呆子化。只是让你知道我不是在批评你基于语义的选择。我只是对更广泛的层面感到好奇。
    【解决方案2】:

    你可以这样做:

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

    这是一个正在运行的 stackblitz 项目:https://stackblitz.com/edit/angular-opc8yg

    【讨论】:

      【解决方案3】:
      const btn: {[keys: string]: string} = {
          key: 'value',
          anotherKey: 'anotherValue'
      }
      

      这个例子应该对你有所帮助。

      【讨论】:

        猜你喜欢
        • 2020-04-23
        • 1970-01-01
        • 2021-02-02
        • 1970-01-01
        • 2021-09-19
        • 2012-09-10
        • 2021-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多