Skip to content

Return type of a function gets incorrectly inferred when nesting a case in an if #31653

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
archaeron opened this issue May 29, 2019 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@archaeron
Copy link

Return type of a function gets incorrectly inferred when nesting a case in an if.

I have reproduced this with typescript@next (3.5.0-dev.20190529)

Search Terms:
switch + return type
switch + noImplicitReturns

Code

with the compiler option noImplicitReturns:

export type Q = { type: "A" } | { type: "B" };

export function f1(q: Q | undefined): string {
  if (q) {
    switch (q.type) {
      case "A":
        return "A";
      case "B":
        return "B";
    }
  } else {
    return "nothing";
  }
}

export function f2(q: Q | undefined): string {
  if (q) {
    return f2_help(q);
  } else {
    return "nothing";
  }
}

function f2_help(q: Q): string {
  switch (q.type) {
    case "A":
      return "A";
    case "B":
      return "B";
  }
}

Expected behavior:

I'd expect both f1 and f2 to compile, since I can get f1 by inlining f2_help into f2.

Actual behavior:

But f1 gives me an error:

Error:

testcase.ts:3:39 - error TS7030: Not all code paths return a value.

3 export function f1(q: Q | undefined): string {
                                        ~~~~~~

Found 1 error.

Playground Link:

NOTE: this only fails with noImplicitReturns turned on in the option (the option does not get saved in the url)

Playground

Repository reproducing the issue

https://github.com/archaeron/typescript-testcase

Related Issues:

Might be related: #31495

@RyanCavanaugh
Copy link
Member

Duplicate #11572

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jun 13, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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