Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
Typescript error: Type 'Document[]' is not assignable to custom type

There is a simple nestJS service, which returns the result of a mongoDb query. As you can see, I tried to set the expected result type, which is an array of documents.

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
} 

But I do get the TS error

Type 'Document[]' is not assignable to type 'MyDataset[]'.
Type 'Document' is missing the following properties from type 'MyDataset': group, location, type, reported

I don't see, what I am doing wrong. Could somebody explain the problem?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The error implies a mismatch between the type you're expecting MyDataset and the one Collection.find({}).toArray() is returning. The mongo db documentation states the toArray() methods returns an array of Documents.

This replicates the same behaviour:

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
};

This will error out with the following 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)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda