Skip to content

(nullable?.methodOrProperty ?? defaultValue) === defaultValue should be a type guardΒ #58196

@tats-u

Description

@tats-u

πŸ”Ž Search Terms

  • type guard
  • nullish coalescing (??)
  • optional chaining
  • default value

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Type Guards

4.9 & Playground

⏯ Playground Link

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcAUAjAhgJwFyIDOUOMYA5gNoC6iAPomCADbP2LgAmApsGd5wCUiAN4AoRJMQ5uUEDiSZcAfgB0zbhSgALRMuWIADMICEAXjNHEAMmuIAslh3q45JTnWbyOwQG4xAL5AA

πŸ’» Code

function foo(bar: string[] | null | undefined) {
    return (bar?.length ?? 0) !== 0 && Math.log(bar.length);
}

πŸ™ Actual behavior

'bar' is possibly 'null' or 'undefined'.

πŸ™‚ Expected behavior

No errors

Additional information about the issue

Math.log(bar.length) can be a React component in real applications.

I have to write the following instead as of now:

function foo(bar: string[] | null | undefined) {
    return bar != null && bar.length !== 0 && Math.log(bar.length);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions