简体   繁体   English

来自常量配置的接口属性名称 object

[英]Interface property name from a constant configuration object

I have an external service that varies it API payloads slightly depending on the installation due to custom fields with numerical id's.由于带有数字 id 的自定义字段,我有一个外部服务会根据安装情况略微改变 API 有效负载。 I've been rolling with the first example until now, but now I want clean up the configuration files a bit.到目前为止,我一直在使用第一个示例,但现在我想稍微清理一下配置文件。 Is there any way to group my constants together in an object without getting a type error?有什么方法可以将我的常量组合在 object 中而不会出现类型错误?

    // No Problem
    const DEV_WIDGET_FIELD_NAME = 'customfield_723'
    interface ApiPayload {
      [DEV_WIDGET_FIELD_NAME]: WidgetType // No problem
    }

    // A computed property name in an interface must refer to an 
    // expression whose type is a literal type or a 'unique symbol' type.
    interface WidgetType {
      a: string;
    }

    interface ConfigType {
      WIDGET_FIELD_NAME: string
    }

    const DEV_CONFIG: ConfigType = {
      WIDGET_FIELD_NAME: 'customfield_723'
    } as const
    interface ApiPayload {
      [DEV_CONFIG.WIDGET_FIELD_NAME]: WidgetType
    }

Edited: I didn't have the ConfigType in my original example.已编辑:我的原始示例中没有 ConfigType。 Taking it out makes this work as I expected.把它拿出来使这项工作如我所料。

Thanks to @jcalz comments and some experimentation, it looks like annotating the DEV_CONFIG constant with a type made things go a bit wonky.感谢@jcalz 的评论和一些实验,看起来用类型注释DEV_CONFIG常量使 go 有点不稳定。 Removing that makes the constant object work as expected.删除它会使常量 object 按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM