Skip to content

Use control flow analysis for type guards #2388

Closed
@jednano

Description

@jednano

TS 1.4

Type guard fails to narrow the union type when returning early.

function foo(x: number | string) {
    if (typeof x === 'string') {
        return;
    }
    // x should now be a number
    if (2 % x !== 0) {
        // do something
    }
}

Unfortunately, I get the following compiler error:

The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

Clearly, the compiler should know at this point that it can't possibly be dealing with a string, as that scenario has already been returned.

Metadata

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueFixedA PR has been merged for this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions