Skip to content

Is this a regression in control flow-based type analysis for --strictNullChecks? #25109

Closed
@seanpoulter

Description

@seanpoulter

TypeScript Version: 2.9.2

Search Terms: typeof undefined guard property strictnullchecks

Code

With --strictNullChecks:

const obj: { [key: string]: string | undefined } = {}

const withAssignment = (key: string): string | null => {
    const value = obj[key];
    return typeof value === 'undefined'
        ? null
        : value;  
}

const withTernary = (key: string): string | null =>
    return typeof obj[key] === 'undefined'
        ? null
        : obj[key];
// Type 'string | null | undefined' is not assignable to type 'string | null'.
// Type 'undefined' is not assignable to type 'string | null'.

const withIf = (key: string): string | null => {
    if (typeof obj[key] === 'undefined') {
        return null;
    } else {
        return obj[key];
        // Type 'string | undefined' is not assignable to type 'string | null'.
        // Type 'undefined' is not assignable to type 'string | null'.
    }
}

Expected behavior:

  • Just like the example in the docs but with an undefined instead of a string.
  • No error.
  • No additional explicit check.
  • The property does not change in this simple statement so the type assertion should be OK.

Actual behavior: 😓
untitled

Playground Link:
http://www.typescriptlang.org/play/#src=...

Related Issues:

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