![](/img/trans.png)
[英]Select property name from object in typescript via interface
[英]Interface property name from a constant configuration object
由于带有数字 id 的自定义字段,我有一个外部服务会根据安装情况略微改变 API 有效负载。 到目前为止,我一直在使用第一个示例,但现在我想稍微清理一下配置文件。 有什么方法可以将我的常量组合在 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
}
已编辑:我的原始示例中没有 ConfigType。 把它拿出来使这项工作如我所料。
感谢@jcalz 的评论和一些实验,看起来用类型注释DEV_CONFIG
常量使 go 有点不稳定。 删除它会使常量 object 按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.