Skip to content

Nullish Coalescing / Order of Operations seems wrong #39096

@dhorkin

Description

@dhorkin

I believe I have found an issue similar to the one mentioned was fixed here: https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#breaking-changes

TypeScript recently implemented the optional chaining operator, but we’ve received user feedback that the behavior of optional chaining (?.) with the non-null assertion operator (!) is extremely counter-intuitive.

I believe there's a similar issue with nullish coalescing not following intuitive order of operations; addition, etc, appear to be prioritized over nullish coalescing, meaning you have to add parenthesis most of the time, rather than on occasion.

TypeScript Version: v3.9.2, v4.0.0-dev.20200615

Search Terms: nullish coalescing

Code

let foo: number | undefined = 10
console.log((foo ?? 1) + 3) // prints 13, as expected
console.log(foo ?? (1 + 3)) // prints 10, as expected
console.log(foo ?? 1 + 3) // prints 10, not 13... Implementation bug?

console.log((foo ?? 0) >= 5) // prints true
console.log(foo ?? 0 >= 5) // prints 10... I think this is (sorta) a separate issue https://github.com/microsoft/TypeScript/issues/36393

foo = undefined // these examples all work as expected
console.log((foo ?? 1) + 3) // prints 4
console.log(foo ?? (1 + 3)) // prints 4
console.log(foo ?? 1 + 3) // prints 4

console.log((foo ?? 0) >= 5) // prints false
console.log(foo ?? 0 >= 5) // prints false

Expected behavior:
?? should be processed before most other operators

Actual behavior:
?? happens last, meaning you must (value ?? valueIfUndefined) + ..., but those parenthesis aren't intuitive.

Playground Link: Playground Link

Related Issues:
#36031
https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#breaking-changes
#36393

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions