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. 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]
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
type IConfig = {
default: IIndividualConfig; // <= Causing error
[key in CID]?: IIndividualConfig;
}
Possible Workaround 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. Hence may want to look at option 2
Workaround 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.