简体   繁体   中英

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. 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?

    // 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. 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. Removing that makes the constant object work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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