#Object is possibly undefined even after if check

6 messages · Page 1 of 1 (latest)

chilly cosmos
#

Hello,

I have the piece of code where I check if interaction.message.attachments.first() is undefined since first() returns Attachment | undefined; however, even after my if, Typescript emits an error saying that the object is still possibly undefined.

While I am aware I can add an optional-chaining operator, that would also require me to do as string, which I don't see the point of doing if Typescript is (or in this case should) be able to assert that interaction.message.attachments.first() is not undefined.

if (!interaction.message.attachments.first()) {
    interaction.reply(
      generateErrorMessage({
      title: "No Embed Data",
      description: "Unable to get embed file from message.",
    })
  )
  return
}

let embedData = fetchExternalFile(interaction.message.attachments.first().url, "json")
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                  Object is possibly 'undefined'. ts(2532)
.catch((error) => {
  logger.thrownError(error)
})

What am I missing here?

restive tusk
#

Save the result of .first() into a variable, check and use that instead.

#

It’s a method call, there’s no guarantee that it returns the same value in multiple calls.

chilly cosmos
#

Alright, thank you

#

i felt like an idiot

#

!solved