Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript Object is possibly undefined in similar cases

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading