[英]Typescript error: Type 'Document[]' is not assignable to custom type
有一个简单的 nestJS 服务,它返回 mongoDb 查询的结果。 如您所见,我尝试设置预期的结果类型,即文档数组。
class MyDataset {
group: string
location: string
type: string
reported: Date
}
async getDatasets(): Promise<Array<MyDataset>> {
const Collection = this.db.collection('collection')
const result = await Collection.find({}).toArray()
return result // <-- ts error
}
但我确实得到了 TS 错误
Type 'Document[]' is not assignable to type 'MyDataset[]'.
Type 'Document' is missing the following properties from type 'MyDataset': group, location, type, reported
我不明白,我做错了什么。 有人可以解释这个问题吗?
该错误意味着您期望MyDataset
的类型与返回的Collection.find({}).toArray()
类型不匹配。 mongo db 文档说明toArray()方法返回一个文档数组。
这复制了相同的行为:
type DocumentA = {
group: string
location: string
type: string
reported: Date
}
type DocumentB = {
anotherField: string
}
const arrayOfDocumentsA = () => {
const res: DocumentA[] = [];
return res;
}
const arrayOfDocumentsB = () => {
const res: DocumentB[] = [];
return res;
}
const getDatasets = (): Array<DocumentA> => {
return arrayOfDocumentsB(); // ts error
};
这将出现以下错误:
Type 'DocumentB[]' is not assignable to type 'DocumentA[]'.
Type 'DocumentB' is missing the following properties from type 'DocumentA': group, location, type, reported ts(2322)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.