Skip to content

Compiler ignores 'instanceof' type guard after throwing an error #53513

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
Hanaasagi opened this issue Mar 26, 2023 · 1 comment
Closed

Compiler ignores 'instanceof' type guard after throwing an error #53513

Hanaasagi opened this issue Mar 26, 2023 · 1 comment

Comments

@Hanaasagi
Copy link

Bug Report

πŸ”Ž Search Terms

throw Error, never, instanceof, TS2339, Unreachable

πŸ•— Version & Regression Information

TypeScript Version 5.0.2

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

I am using instanceof in a piece of code to execute different operations based on the type of a variable. The code can be compiled successfully after commenting out the unimplemented function call. However, if I use unimplemented to throw an exception, the type information is missing . In this case, the compiler throws TS2339.

interface IValue {}

class Integer implements IValue {
  val: number;

  constructor(val: number) {
    this.val = val;
  }
}

function unimplemented(msg: string): never {
  throw new Error("It's unimplemented! " + msg);
}

function dispatch(x: IValue): number {
  unimplemented('function dispatch');

  if (x instanceof Integer) {
    return x.val;
  }

  return 0;
}

πŸ™ Actual behavior

2023-03-27_00-37

Property 'val' does not exist on type 'IValue'. is reported.

πŸ™‚ Expected behavior

The code can be compiled successfully even if there is unreachable code, and the type check of instanceof should not be ignored.

@fatcerberus
Copy link

Duplicate of #26914.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants