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

Type Guarding breaks with functions that return never #39578

Closed
kwasimensah opened this issue Jul 13, 2020 · 2 comments
Closed

Type Guarding breaks with functions that return never #39578

kwasimensah opened this issue Jul 13, 2020 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@kwasimensah
Copy link

TypeScript Version: 3.7.x-dev.201xxxxx

Search Terms:

never type guard

Code

function fooWorking(x: number | undefined) : number {
  if (x === undefined) {
    throw new Error("Is undefined");
  }
  return x;
}


function fooBroken(x: number | undefined): number {
  const isAnError = () => {
    throw new Error("Is undefined");
  }
  if (x === undefined) {
    isAnError();
  }
  return x; // errors because it can't tell that x can only be a number
}

Expected behavior:

fooBroken compiles without issue. Typescript can tell that x must be a number because the if branch calls a function that never returns.

Actual behavior:

Typescript complains on the return statement in fooBroken because it doesn't realize x can only be a number.

Playground Link:

https://www.typescriptlang.org/play/?ssl=17&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABMOcDqcBOBrGYDmAFAB4BciYIAtgEYCmmiAPouACZ3B51sCUi5SrQaIA3gChEiGMEQlEAXiWswHLmB78JUqVAAWmOAHcKdEwFFMhzIQBEASQDOKtdza3eAbkmIAvj8w6KBBMJGJvf3FxUEhYBGRUACFDbDowEkFqekYWdk43XkzhRm1ECARHKGlHAEEwS2tFOX4FAD4xH10DY1MLKyw7Jxd8jXcvH38pGTliRWU89U0OnWq6hoHxqUnEQODQxHDEAHojxAZrZ3oIAEMQRzppKpuwAHIqqDoAG0-EfWuq2bPRAIT4AT0Q9EQ1woWQY4l8QA

Related Issues:

@MartinJohns
Copy link
Contributor

MartinJohns commented Jul 13, 2020

Duplicate of #12825.

You can use assertions instead: #32695

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jul 13, 2020
@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

4 participants