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

237
Visualizações
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 Respostas
Responde à pergunta

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