0
type Person = {
    account?: {
        money: number
    }
}

const person: Person = {}

// case1 - this is not error
if (person.account?.money === 0) {
    console.log("I have no money");
}

// case2 - Object is possibly 'undefined'.(2532)
if (person.account?.money > 0) {
    console.log("I have money!!");
}

Why does not typescript show error on case 1, but only case 2?
What's difference?

1 Answer 1

2

You can't do mathematical comparisons (<,>, <=, >=) with optional variables, it makes no sense and Typescript is reminding you to specify what to do in the situation.

> undefined < 1
  // false
> undefined > 1
  // false

This rule is enabled by the strictNullChecks option.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, How about this? if (person.account?.money > 0) { console.log(person.account.money); => // Object is possibly 'undefined'.(2532) why?? } I think person.account cannot be undefined
If the compiler is complaining, a field has to be optional, maybe money is ?
I think that if person.account?.money > 0 is ture, then we can sure that person.account is never undefined. Check this link please!
remove the > 0 part and you have you fix. First check for person.account to be defined.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.