[英]A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type
Ultimately I would like to compute something as below最终我想计算如下
const configOne = {
default: {master: 0},
sg: {master: 1},
}
const configTwo = {
default: {master: 1}
}
Basically the object
must have the default
as mandatory properties, then the remaining properties can be optional, but they must be of country prefix.基本上
object
必须有default
的强制属性,然后其余属性可以是可选的,但它们必须是国家前缀。 Below is the attempt I have以下是我的尝试
enum CID {
'tw',
'sg',
'vn',
}
interface IIndividualConfig {
master: 0 | 1;
}
type IConfig = {
default: IIndividualConfig;
[key in CID]?: IIndividualConfig;
}
const configOne: IConfig = {
default: { master: 0 },
sg: {master: 1}
}
const configTwo: IConfig = {
default: { master: 1 }
}
And below is the error I've got at [key in CID]
下面是我在
[key in CID]
处遇到的错误
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The problem occurs because you've defined default
in the definition while using index signature
such as below出现问题是因为您在使用如下
index signature
时在定义中定义了default
type IConfig = {
default: IIndividualConfig; // <= Causing error
[key in CID]?: IIndividualConfig;
}
Possible Workaround 1:可能的解决方法 1:
type IConfig = {
[key in CID | 'default']?: IIndividualConfig;
}
This will not gives you error, but probably doesn't 100% fit the use case, since default
is no longer mandatory.这不会给你错误,但可能不会 100% 适合用例,因为
default
不再是强制性的。 Hence may want to look at option 2因此可能想看看选项 2
Workaround 2:解决方法 2:
type IDefaultConfig = { default: IIndividualConfig; }
type IConfig = IDefaultConfig & {[key in CID]?: IIndividualConfig; };
Now by using intersection
, we combined two types into a single type, default
will be mandatory, and other key are optional and they must be of type CID
if defined现在通过使用
intersection
,我们将两种类型组合成一个类型, default
是强制的,其他键是可选的,如果定义它们必须是CID
类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.