Skip to content
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

Feature request: better process function exits for type guards and 'if'-s #2654

Closed
zhuravlikjb opened this issue Apr 7, 2015 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@zhuravlikjb
Copy link

Currently type guards are limited only to bodies of conditionals.

A simple example with 'if':

function f(s: string | number) {
      if (typeof s === "string") {
          // s is 'string'
      }
      else {         
          // s is 'number'
      }
}

But what if I write the same code, but another way:

function f(s: string | number) {
      if (typeof s === "string") {
          // s is 'string'
          // do something
          return;
      }

      // s is 'string | number', according to the compiler
      // but control flow of 'if' block flows directly to a function exit
      // that's why, s is actually 'number' here, if no assignments are made
}

So, the suggestion is to augment the rule for 'if' as follows:

  • If the false branch is not present, and all control flow exits of the true branch point exactly to function exits, the type of a variable or parameter is narrowed by a type guard in the code after 'if' statement when false, provided the code after 'if' statement contains no assignments to the variable or parameter.
  • If all control flow exists of the false branch point exactly to function exits, the type of a variable or parameter is narrowed by a type guard in the code after 'if' statement when true, provided the code after 'if' statement contains no assignments to the variable or parameter.
@mhegazy
Copy link
Contributor

mhegazy commented Apr 7, 2015

looks like the same as #2388

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Apr 7, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants