【发布时间】:2020-09-04 19:56:49
【问题描述】:
我有一个字符串字面量数组,我想将其用作类的属性名称。
const propNames = ["a", "b", "c"] as const;
我想创建一个类
class Test {
[name in typeof propNames[number]]: any;
}
但这会产生错误(在 WebStorm 检查中):
TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.
TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.
TS2693: 'number' only refers to a type, but is being used as a value here.
我可以用这些属性定义一个类型,例如
type Test = {
[name in typeof propNames[number]]: any;
}
但我不知道如何将它变成具有这些属性的类。
我有一个我认为目前不可能的额外问题,但我可以通过将另一个字符串文字连接到它们来创建这些属性名称吗?
type Test = {
[name + 'Prop' in typeof propNames[number]]: any;
}
【问题讨论】:
标签: typescript literals computed-properties