【发布时间】:2022-06-12 05:02:37
【问题描述】:
我这样声明一个类:
declare class MyClass {
key: string
data: {
[this.key]: string; // error: A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.
otherProps: { [k: string]: number | undefined; }
}
}
预期的行为是应该键入data 对象,以便如果键等于传递给构造函数的键,则它映射到一个字符串。这是因为我想实现以下目标:
class MyClass {
myFunction () {
const value1 = this.data[this.key] // value1 should be type string
const value2 = this.data.otherProps.foo // value2 should be type number | undefined
}
}
但是,这不起作用并引发错误,如第一个 sn-p 中的注释所示。我怎样才能做到这一点?
【问题讨论】:
-
你至少有一个错字(你不能在
declare class中实现构造函数),你能确保这表明你的问题,而且只有在 IDE 中查看时你的问题? -
这里有两个不同的问题,为了获得最佳结果,您应该编辑您的问题以专注于其中之一。第一个是您需要
data属性在键this.key处具有强类型属性。第二个是您希望data属性具有任意数量的string类型的number | undefined键,除了 的单个键不符合该键。这第二位是不可能直接实现的,我会指向this question 来查看选项。那么,这些问题中的哪一个是您的问题的重点? -
顺便说一下,this approach 是我处理你的第一个问题的方式(注意我是如何通过将其他冲突的道具移到
otherProps属性来回避第二个问题的)。如果这满足您的需求,我可以写一个答案。 -
@jcalz 哎呀我没有注意到这里不允许使用构造函数,但我添加它只是为了表明我有一个实例变量
private key: string。构造函数不在我的实际declare class中。我也没有意识到我在我的问题中提出了两个不同的问题,但重点是你描述的第一个问题。您在 TS Playground 上的方法对我有用,您可以将其添加为答案! :) -
如果有人调用
new MyClass("otherProps")那么你会想要一个错误,从那时起otherProps属性现在应该是一个字符串和一个字典,它不能同时是这两者。如果你不关心它,你可以把它关掉。
标签: typescript