【发布时间】:2021-10-02 09:09:24
【问题描述】:
如何在接口中声明强制一个对象扩展另一个对象?
场景: 我收到一个 JSON 对象(称为文档),其中 document.children 是一个始终具有 _id、_ref 和 _type 以及特定于其 _type 的附加字段的对象数组。
目前有 4 种不同的类型,但这种类型会增长,理想情况下我不希望未来的开发者担心编辑文档界面
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',
},
],
};
【问题讨论】:
标签: typescript interface