Typescript: No narrowing on condition captured by const variable

Created on 11 Aug 2020  ·  4Comments  ·  Source: microsoft/TypeScript

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

Duplicate

Most helpful comment

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
}

All 4 comments

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

Duplicate of #12184.

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
}

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

weswigham picture weswigham  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments

jbondc picture jbondc  ·  3Comments

blendsdk picture blendsdk  ·  3Comments

fwanicka picture fwanicka  ·  3Comments