-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Incorrect ts(18048) (possibly 'undefined' error) after optional chaining with const #53872
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Narrowing only occurs based on expressions involving the variable in question (i.e. it's not a constraint-solving system). Since |
If you change |
True, there is one level of back-propagation on optional chains |
Not sure if this is related or not. TypeScript 5.1.3. Found this issue when working on Maps with class that has a function as values, tried playground and got it reproduced. class Hello extends Map<string, World> {
doStuff(key: string) {
const value = this.get(key);
const one = value?.doStuffOne();
if (!one) return undefined;
value.doStuffTwo(); // <-- ts(18048) 'value' is possibly undefined.
if (one) {
value.doStuffTwo(); // <-- ts(18048) 'value' is possibly undefined.
}
}
}
class World {
doStuffOne() {
return true;
}
doStuffTwo() {
return true;
}
} I'm sure that class Hello extends Map<string, World> {
doStuff(key: string) {
const value = this.get(key);
if(value?.doStuffOne()) value.doStuffTwo();
}
}
class World {
doStuffOne() {
return true;
}
doStuffTwo() {
return true;
}
} |
Just wanted to chime in an another example that would perhaps illustrate the problem an an even more obvious manner:
I would suggest that the title of this issue could be changed to: Type narrowing disrupted by preceding "throw" statement (TS18048) |
Bug Report
🔎 Search Terms
ts(18048)
is possibly 'undefined'.
optional chaining
🕗 Version & Regression Information
Verified bugged in 4.9.5 through 5.0.4 and the most recent Nightly as of this posting.
(The same code throws a different ts error earlier than 4.9.5.)
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
'obj' is possibly 'undefined'.(18048)
at the final return line for 'obj'🙂 Expected behavior
No typescript error should be shown here, because 'obj' can never be undefined since 'foo' and 'a' would then also be undefined so the code would never reach the final return.
The text was updated successfully, but these errors were encountered: