Skip to content

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

@zhuravlikjb

Description

@zhuravlikjb

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions