I am working with an interface that contains an array of itself as children elements.
interface MyNestedInterface {
value: string;
children?: ReadonlyArray<MyNestedInterface>;
}
My goal is to ensure that the objects are only one level deep in the structure.
interface MyNestedInterface {
value: string;
children?: ReadonlyArray<Omit<MyNestedInterface, 'children'>>;
}
In addition, I need to extend the MyNestedInterface
interface.
interface ExtendedInterface extends MyNestedInterface {
id: string;
}
However, when trying to instantiate it with an as const
, I encounter an error related to the children property not recognizing the extended property id
.
const obj: Readonly<ExtendedInterface> = {
id: 'id1',
value: 'value1',
children: [
// Error: Object literal may only specify known properties, and 'id' does not
// exist in type 'Pick<MyNestedInterface, "value">'.
{ id: 'id2', value: 'value2' },
{ id: 'id3', value: 'value3' },
],
} as const;
Is there a way to reference this
inside the MyNestedInterface
so that it recognizes the extended properties, or is there a different approach to overcome this issue without redefining children
in the ExtendedInterface
?