Closed
Description
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