How do I have a declaration inside an interface that enforces an object to extend another?
Scenario: I receive a JSON object (called document) where the document.children is an array of objects that will always have _id, _ref and _type, as well as additional fields that are specific to its _type.
Currently There are 4 different types but this will grow and ideally i don't want future devs having to worry about editing the Document interface
export interface BaseRefs {
_id: string;
_ref: string;
_type: string;
}
export interface Span extends BaseRefs {
text: string;
}
export interface MainImage extends BaseRefs {
url: string;
caption: string;
}
export interface Document extends BaseRefs {
_createdAt: string;
_rev: string;
_updatedAt: string;
children: // Any object that extends BaseRefs
// children: MainImage | Span | Carousel | ........ | Video[] // This is not ideal
}
export const document: Document = {
_createdAt: '2019-12-12T04:14:18Z',
_id: 'c9b9-4cd0-a281-f6010f5889fd',
_ref: 'ej2gcz5m4',
_rev: 'nwyfsi--ej2gcz5m4',
_type: 'post',
_updatedAt: '2020-01-16T11:22:32Z',
children: [
{
_type: 'span',
text: 'The rain in Spain',
},
{
_type: 'mainImage',
url: 'https://example.com/kittens.png',
},
],
};