Skip to content

exactOptionalPropertyTypes does not include undefined in the type for assignment operators like ??=Β #53305

Closed
@bradzacher

Description

@bradzacher

Bug Report

πŸ”Ž Search Terms

assignment operator, noUncheckedIndexedAccess

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

// @exactOptionalPropertyTypes

declare const xx: { prop?: number };

xx.prop;
//  ^?
// typeof xx.prop === number | undefined βœ…

function aa() {
xx.prop.toFixed();
//  ^?
// typeof xx.prop === number | undefined βœ…
}

function bb() {
xx.prop += 1;
//  ^?
// typeof xx.prop === number | undefined βœ…
}

function cc() {
xx.prop ??= 1;
//  ^?
// typeof xx.prop === number ❌
}

function dd() {
xx.prop ?? (xx.prop = 1);
//  ^?
// typeof xx.prop === number | undefined βœ…
}

function ee() {
xx.prop = 1;
//  ^?
// typeof xx.prop === number ❌
}

πŸ™ Actual behavior

TS reports the type of xx.prop to be just number when using the ??= assignment operator.
This is incorrect - xx.prop might be undefined until AFTER the assignment and also is different behaviour compared to other assignment operators and different to how the expanded assignment is typed.

πŸ™‚ Expected behavior

TS reports the type of xx.prop to be number | undefined before the assignment.

Additional info

In addition to the above - this behaviour makes it difficult for us to write lint rules because when we attempt to check if the LHS of the assignment is undefined, the type system reports that it is not. Example issue typescript-eslint/typescript-eslint#6635

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions