Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda