Skip to content

! does not narrow discriminated unions when strict is false #63686

Description

@LancesLance56

Search Terms

Tested on:

  • TypeScript 6.0.3
  • TypeScript 7.0.2

with "strict": false in compilerOptions

https://www.typescriptlang.org/play/?strict=false&jsx=0&ssl=13&ssc=2&pln=2&pc=1#code/C4TwDgpgBAShDOBXANsKBeAUFKAfKA3lAPYDWAXFMAE6IQDcUAbgIbJ2Xw0CWAdgOZQAvtjyESFKADM28BlAjVqxapx4Dh9TJgAmEAMbIW1aPuK8uUE0lSU4N4FszcpUABQBCaymAA6MgCUhKLeqL6KytSMAPTRUAAKypDUoFAA5BEqaVA6xAhQvMRoEAAe3FyYIs6ubqF+ZBjo6NKyEEEEIQg+4UoqMXEA6iqk8JVAA

type Result =
  | { ok: true; value: string }
  | { ok: false; error: string };

declare const result: Result;

if (!result.ok) {
  result.error; // Property 'error' does not exist
}

if (result.ok === false) {
  result.error; // Works
}

Actual behavior

When strict is false, !result.ok does not narrow the discriminated union, while result.ok === false does.

Expected behavior

if (!result.ok) should narrow result to the { ok: false; error: string } branch, just like if (result.ok === false).

Additional information about the issue

Not sure whether this is intended behavior or a bug. Either way would love to learn why

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions