Skip to content

No narrowing on condition captured by const variable #39996

Closed

Description

@amannn

TypeScript Version: 4.0.0-beta

Search Terms:

  • "unnecessary null check"
  • "derived boolean null check"

Expected behavior:

When a created variable contains a null check, using that boolean should be sufficient for safe access to the variable.

Actual behavior:

TypeScript needs an additional null check.

Related Issues:

Code

export default function foo(a: {b: boolean} | undefined) {
    const isNull = a == null;

    if (isNull) {
        return;
    }

    // Object is possibly 'undefined'.
    return a.b
}
Output
export default function foo(a) {
    const isNull = a == null;
    if (isNull) {
        return;
    }
    return a.b;
}
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

Activity

  1. amannn commented on Aug 11, 2020

    @amannn
    Author

    My apologies if this issue already exists, I couldn't find it with my search terms! Thanks for your help!

  2. MartinJohns commented on Aug 11, 2020

    @MartinJohns
    Contributor

    Duplicate of #12184.

  3. tom-sherman commented on Aug 11, 2020

    @tom-sherman

    You can use a type guard instead:

    function isNullish<T>(x: T | null | undefined): x is null | undefined {
        return x == null;
    }
    
    declare const x: number | undefined;
    
    if (!isNullish(x)) {
        x // number
    }
  4. changed the title [-]Derived boolean null check[/-] [+]No narrowing on condition captured by const variable[/+] on Aug 13, 2020
  5. typescript-bot commented on Aug 16, 2020

    @typescript-bot
    Contributor

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

  6. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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