Typescript error: Type 'Document[]' is not assignable to custom type
Typescript error: Type 'Document[]' is not assignable to custom type
有一个简单的 nestJS 服务,returns 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() 方法 returns 文档数组。
这复制了相同的行为:
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)
有一个简单的 nestJS 服务,returns 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() 方法 returns 文档数组。
这复制了相同的行为:
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)