Skip to content

asserting "false is NonNullable<boolean>" triggers unreachable code detection #40017

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
max-vogler opened this issue Aug 12, 2020 · 4 comments
Closed

Comments

@max-vogler
Copy link

TypeScript Version: 3.8.2, 3.9.2

Search Terms: unreachable code, asserts, assertion, nonnullable, type guard

Expected behavior: The code compiles without warnings.

Actual behavior: Any code after assertNonNull(false) is marked as unreachable.

Related Issues: -

Code

function assertNonNull<T>(value: T): asserts value is NonNullable<T> {
  if (value === null || value === undefined) {
    throw new Error(`Expected value to be non-nullable, but got ${JSON.stringify(value)}`);
  }
}

assertNonNull(0);
assertNonNull('');
assertNonNull(false);
console.log("end"); // Unreachable code detected.
Output
"use strict";
function assertNonNull(value) {
    if (value === null || value === undefined) {
        throw new Error(`Expected value to be non-nullable, but got ${JSON.stringify(value)}`);
    }
}
assertNonNull(0);
assertNonNull('');
assertNonNull(false);
console.log("end"); // Unreachable code detected.
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

@mprobst
Copy link
Contributor

mprobst commented Aug 12, 2020

I think this is only reported as unreachable with allowUnreachableCode: false, right?

@max-vogler
Copy link
Author

tsc reports a hard error TS7027: Unreachable code detected. for allowUnreachableCode: false. If the config option is undefined or true, tsc compiles the code without errors. This is expected per tsconfig#allowUnreachableCode, but still does not explain the unexpected behavior of my issue.

@jack-williams
Copy link
Collaborator

Did you try master? Looks to be a duplicate of #38699 which is now fixed.

@max-vogler
Copy link
Author

You're right. Switching to 4.0.0-beta in the playground removes the error.

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

3 participants