Skip to content

No narrowing on condition captured by const variable #39996

Closed
@amannn

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

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