Description
π Search Terms
look ahead
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
To (optionally, disabled by default) add more look-ahead logic in the typescript engine
π Motivating Example
function updateCanvasTime() {
if (!canvasElm || !ctx) {
error = true;
return;
} else {
error = false;
}
ctx.strokeStyle = 'white';
}
The above code works fine:
function updateCanvasTime() {
error = !canvasElm || !ctx;
if (error) return;
ctx.strokeStyle = 'white';
}
However, when we extrapolate it into a variable to clean it up, then TS doesn't like this:
"'ctx' is possibly 'null'.ts(18047)"
Of course, I could just write ctx!.strokeStyle = 'white';
for every usage of ctx
within the function, but this would go against the TS goal of making things easier on the user.
I realize 1) that this could add overhead, and I am certainly no expert here, but I would suggest making the setting off by default and an option that can be enabled. I also realize 2) that this may not be worth the effort to implement, in which case, ok. It's simply an idea, not something I think is crucial. But I do think it would improve developer experience.
Thanks for listening and for all the work you do on TS!
π» Use Cases
What do you want to use this for?
Writing cleaner code / less verbose code without getting TS errors everywhere.
What shortcomings exist with current approaches?
TS doesn't "know" about variables that are defined above that check if an element exists or meets a certain value / criterion.
What workarounds are you using in the meantime?
Currently just using the longer code. My example isn't as big of a deal, but in cases where the logic is more advanced, I can see this being a big improvement.