Skip to content

Flow-sensitive type narrowing does not extend into closures that are created after the narrowing is applied #37802

Closed
@dead-claudia

Description

@dead-claudia

TypeScript Version: 3.3.3, 3.5.1, 3.6.3, 3.7.5, 3.8.2, 3.9.0-beta, and 3.9.0-dev.20200328 (every version in the playground at the time of writing)

Search Terms: flow-sensitive type closure

Expected behavior: No type errors

Actual behavior: In the return value for deferred, I got this error:

Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'. (2322)

Related Issues: Couldn't find any

Code

function immediate(value?: string): string {
    if (value == null) {
        value = "";
    }

    return value;
}

function deferred(value?: string): () => string {
    if (value == null) {
        value = "";
    }

    return (): string => {
        return value;
    };
}
Output
"use strict";
function immediate(value) {
    if (value == null) {
        value = "";
    }
    return value;
}
function deferred(value) {
    if (value == null) {
        value = "";
    }
    return () => {
        return value;
    };
}
Compiler Options
{
  "compilerOptions": {
    "strict": true,
  }
}

Playground Link: For nightly, but you can verify with other versions easily enough.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions