gpt4 book ai didi

javascript - typescript 错误 : Type 'Document[]' is not assignable to custom type

转载 作者:行者123 更新时间:2023-12-05 08:04:06 24 4
gpt4 key购买 nike

有一个简单的 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 数据库文档说明 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)

关于javascript - typescript 错误 : Type 'Document[]' is not assignable to custom type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70020147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com