Skip to content

Nullish coalescing and conditional type narrowingΒ #48536

Closed as not planned
Closed as not planned
@vlovich

Description

@vlovich

Suggestion

Conditional + nullish coalescing doesn't seem to reify the type correctly.

πŸ” Search Terms

nullish coalescing
nullish coalescing conditional

#43705 sounds maybe related but hard to tell (examples listed don't seem the same)

βœ… Viability Checklist

  • [Y] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [Y] This wouldn't change the runtime behavior of existing JavaScript code
  • [Y] This could be implemented without emitting different JS based on the types of the expressions
  • [Y] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • [Y] This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Conditional type narrowing through the || operator + the use of the nullish coalescing operator should understand each other to reify the type correctly.

πŸ“ƒ Motivating Example

declare function foo(): string | undefined

const a = foo()
const b = foo()
if (a != undefined || b != undefined) {
  const c = a ?? b
}

c should have type string but instead it has type string | undefined because TS hasn't reasoned that the only way into the block is if a ?? b must be non-null.

πŸ’» Use Cases

Came up in my code where I had two strings and each could be string | undefined and I wanted to nullish coalesce but only if one of them was not undefined. Had to use ! as a workaround

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions