【问题标题】:Typescript error: Type 'Document[]' is not assignable to custom type打字稿错误:类型“文档 []”不可分配给自定义类型
【发布时间】:2021-12-29 08:39:18
【问题描述】:

有一个简单的 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

我不明白,我做错了什么。有人能解释一下这个问题吗?

【问题讨论】:

    标签: javascript typescript nestjs


    【解决方案1】:

    该错误意味着您期望的 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)
    

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 2018-02-02
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多