【发布时间】:2021-04-29 10:19:21
【问题描述】:
我正在尝试在我的 Angular 应用程序上重新创建我的猫鼬对象,因此我正在尝试制作接口。 问题是我并不总是发送带有填充字段的对象,所以我有这样的东西:
export interface Action {
_id: string
document: Document | string,
}
export interface Document {
_id: string
...otherFields
}
在我的代码中,我有类似的东西:
const data = {
documentId: action.document?._id
}
但我收到了阻止编译的错误:
Property '_id' does not exist on type 'string'.
那么,如何让它同时适用于这两种类型呢?
【问题讨论】:
-
如果是字符串,你想让它做什么?
-
@NicholasTower 两个接口都来自 mongoDB,document 是 action 对象中的引用。所以如果我做人口,文档是一个对象,但如果不是,它是一个字符串
-
我的意思是,如果
action.document是一个字符串,您希望将data.documentId设置为什么?最有可能的候选者是字符串本身,或者未定义。
标签: angular typescript mongoose types interface