【发布时间】:2021-02-11 18:18:12
【问题描述】:
我有一个包含以下形式的属性名称的对象:
const INPUT_NAMES = {
FIRST_NAME: 'first-name',
LAST_NAME: 'last-name'
};
我想根据这些属性名称值生成一个接口:
interface IPropertyFormat {
[INPUT_NAMES.FIRST_NAME]: string;
[INPUT_NAMES.LAST_NAME]: string;
}
这不起作用,因为我没有使用文字类型,也没有使用符号,我得到了这个:A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
使用一个简单的常量,例如:
const KEY = "FIRST_NAME";
interface IPropertyFormat {
[KEY]: string;
}
有效,但在我的情况下不是一个优雅的解决方案,如果可能的话,我想避免它。我已经查看了this other kinda related topic,但它没有为我的问题提供解决方案。
有人知道如何解决这个问题吗?
编辑:
此外,再次使用 const 断言找到了一个“有点什么”解决方案 at this post。
【问题讨论】:
-
@Nishant 我什至不确定这与我的问题有什么关系。
-
@zhulien 也许我理解错了,但这能解决你的问题吗? tsplay.dev/rw2DYm在重复问题中是一样的
-
@Nishant 是的,这更像它。谢谢你。就像我提到的,
const assertion很有帮助,我不知道这个功能。
标签: typescript