Reputation: 320
I would like to write the proper interface for this object. The key of step should be dynamic and the value is boolean. This is the object:
const obj = {
A: {
step: {
a: true,
b: true,
c: true,
},
},
B: {
step: {
a: true,
d: true,
},
},
C: {
step: {
e: true,
f: true,
g: true,
},
},
}
So far I have tried this, but I still got an error.
interface OBJ_INTERFACE {
side: {
step: {
[key: string]: boolean,
}
}
}
Upvotes: 0
Views: 234
Reputation: 38046
You can extract Step
type and reuse it in interface:
type Side = {
step: {
[key: string]: boolean,
}
};
interface OBJ_INTERFACE {
A: Side;
B: Side;
C: Side;
}
Or define a mapped type:
type OBJ_INTERFACE = {
[P in 'A' | 'B' | 'C']: {
step: {
[key: string]: boolean,
}
}
}
Upvotes: 1
Reputation: 6780
You don't detail the error, so I can only assume it stems from trying to use the interface as such:
const obj: OBJ_INTERFACE = {
A: {
step: {
...
}
}
}
In which case, your interface doesn't account for the side
property being dynamically named as 'A' | 'B' | 'C'
.
Try making side
dynamic as well:
interface OBJ_INTERFACE {
[key: string]: {
step: {
[key: string]: boolean
}
}
}
Upvotes: 1