Skip to content

"Smarter" look ahead logic for variable existingΒ #57733

Closed
@justingolden21

Description

@justingolden21

πŸ” Search Terms

look ahead

βœ… Viability Checklist

⭐ 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:

image


	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:

image

"'ctx' is possibly 'null'.ts(18047)"

image


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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions