Producdevity
Producdevity

Reputation: 882

TS2532: Object is possibly 'undefined' while being assigned on the previous line

I've been looking at the questions and answers regarding this TypeScript error but none of them are the same as the problem as the one I will describe here as far as I know.

The exact error I get is: TS2532: Object is possibly 'undefined'. where self.session had a red squiggly underline

  self.session = {}
  self.session.ready = true

This is the "type" of session:

export const AuthStore = BaseMixin.named('AuthStore')
  .props({
    session: types.maybe(SessionData)
  })

You would think that it's pretty clear the session is initialized at this moment but still TypeScript it might now be. I tried wrapping it in an "if" statement to check if self is initialized but that didn't fix it.

Previously we fixed it using: self.session!.ready = true but that's of course a workaround and not a proper fix.

I think I know TypeScript but TypeScript likes to prove me wrong often.

We're using TypeScript version 4.2.4

Here's a link to codesandbox where I reproduced the same issue: https://codesandbox.io/s/typescript-playground-export-forked-ek721c?file=/index.ts

update (The screenshot is only to show where TypeScript is adding the red underline, I thought this might help since it doesn't normally underline the object and supposed undefined property If I remember correctly)

ts underline

Upvotes: 0

Views: 263

Answers (0)

Related Questions