我有一个字符串文字数组,我想用作一个类的属性名称。
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;
}
为什么不定义类型,然后通过以下方式使用它:
type Test = {
[key: TEST]: any;
}
其中TEST是类型。我从不冒险这样做,但是我知道它适用于原始类型。
希望它可以带您去需要的地方!