Home > database >  typescript Object is possibly undefined in similar cases
typescript Object is possibly undefined in similar cases

Time:07-11

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?

CodePudding user response:

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.

  • Related