Skip to content

Taking variables into account when checking for possible null values TS2532 #42446

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

Closed
5 tasks done
marvinthepa opened this issue Jan 21, 2021 · 1 comment
Closed
5 tasks done
Labels
Duplicate An existing issue was already created

Comments

@marvinthepa
Copy link

marvinthepa commented Jan 21, 2021

Suggestion

I excuse in advance for opening this if this is too expensive too implement.
I think it might be useful to some though.

πŸ” Search Terms

all included below

βœ… Viability Checklist

My suggestion meets these guidelines:

  • 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 feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

If an if statement only contains a single local constant variable, the compiler should inline the variable into the if statement (if the contents can be locally inferred) when checking for undefined variables.
If that sounds complicated to you, I suggest to check out the example below.

πŸ“ƒ Motivating Example

This does not compile:

    const noSelection = !start || !end || (start[0] === end[0] && start[1] === end[1]);
    if (noSelection) {
      if (foo) bar();
      return;
    }

    console.log(start[0]); // Object is possibly undefined ts2532
    // some more code using noSelection

but this does:

    if (!start || !end || (start[0] === end[0] && start[1] === end[1])) {
      if (foo) bar();
      return;
    }

    console.log(start[0]); // No error
    const noSelection = !start || !end || (start[0] === end[0] && start[1] === end[1]);

although they are basically the same code.
The information is there to deduce that start can never be undefined, so it could be used in theory.

πŸ’» Use Cases

This can prevent uneccessary null checks or executing code twice that only needs to be executed once.
Can also help readability. The current workaround is to duplicate the logic

@MartinJohns
Copy link
Contributor

#12184

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants