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

243
Vistas
Typescript gives object might be null error while passing object to function inside promise.then

The following is the code from a request controller function.

Objective I wanted to create different types of notifications depending upon the which paths are modified.

let farmerToUpdate = await FarmerModel.findById(farmerId)
  if (!farmerToUpdate) throw new controllerError('Farmer you want to update is deleted', 422)

  // farmerToUpdate.set(Object.assign(farmerToUpdate, req.body))
  farmerToUpdate.set(req.body)

  let directModifiedPaths = farmerToUpdate.directModifiedPaths()
  const updatedFarmer = await farmerToUpdate.save()

  if (directModifiedPaths.includes('farmerCode') || directModifiedPaths.includes('centreCode')) {
    // farmerToUpdate is original document and updatedFarmer is document after updating
    createNotification(farmerToUpdate, updatedFarmer, ['farmerCode', 'lakshmiCentreCode'], true, 'Codes Updated').then(
      function () {
        directModifiedPaths = directModifiedPaths.filter(d => d !== 'farmerCode' && d !== 'lakshmiCentreCode')
        if (directModifiedPaths.length) {
          createNotification(farmerToUpdate, updatedFarmer, directModifiedPaths, false, 'Plain').then(res => {})
        }
      },
    )
  }

After creating notification of one type when I try to pass same first argument farmerToUpdate to the createNotification function I get following error

Argument of type '(Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; }) | null' is not assignable to parameter of type 'Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; } & { notificationId?: number | undefined; }'. Type 'null' is not assignable to type 'Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; } & { notificationId?: number | undefined; }'. Type 'null' is not assignable to type 'Document<unknown, any, Farmer>'.

If I add check for a valid farmerToUpdate it works fine -

farmerToUpdate && createNotification(farmerToUpdate, updatedFarmer, directModifiedPaths, false, 'Plain').then(res => {})

I wonder why it not gives the same error for second parameter or third???

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The type of farmerToUpdate is nullable, but if (!farmerToUpdate) throw ... makes it non-nullable anymore afterward in the same scope or any descendant scopes. (https://www.typescriptlang.org/docs/handbook/2/narrowing.html)

But the nested function has it's own scope, and in it the farmerToUpdate's type is still nullable.

Ideally, it's maybe possible for the compiler to determine that farmerToUpdate will actually never be null in the nested function, but it is more complex and the compiler just doesn't support that I think.

update:

the return value of await FarmerModel.findById(farmerId) is nullable (in another word: it may return null), and therefor farmerToUpdate is nullable (in another word: it may be null).

But return values of farmerToUpdate.directModifiedPaths() and await farmerToUpdate.save() are non-nullable, and therefor updatedFarmer and directModifiedPaths are both non-nullable (in another word: they'll never be null).

That's why the compiler only compains farmerToUpdate, but not updatedFarmer and directModifiedPaths.

Actually farmerToUpdate.directModifiedPaths() should be farmerToUpdate!.directModifiedPaths(). That's because the type of farmerToUpdate may be null, but we know it'll never be null in that context, therefor we can treat it as non-nullable. The compiler can do that deduction automatically, so we can eliminate the exclamation mark without error.

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