Skip to content

Control flow not formed when using consts #11542

@NoHomey

Description

@NoHomey

TypeScript Version: 2.0.3

Code

interface Releasable {
    release(): void;
}

const typeOfNumber: string = 'number';

function release(releasable: number | Releasable): void {
    if(typeof releasable === typeOfNumber) {
         allocated.splice(allocated.indexOf(releasable), 1);
    } else {
         releasable.release();
    }
}

Expected behavior:

interface Releasable {
    release(): void;
}

const typeOfNumber: string = 'number';

function release(releasable: number | Releasable): void {
    if(typeof releasable === typeOfNumber) {
         allocated.splice(allocated.indexOf(releasable), 1); // Ok, typeof releasable is number here
    } else {
         releasable.release(); // Ok, typeof releasable implements Releasable here
    }
}

Actual behavior:

interface Releasable {
    release(): void;
}

const typeOfNumber: string = 'number';

function release(releasable: number | Releasable): void {
    if(typeof releasable === typeOfNumber) {
         allocated.splice(allocated.indexOf(releasable), 1); // [ts] Argument of type 'number | Releasable' is not assignable to parameter of type 'number'. Type 'Releasable' is not assignable to type 'number'.
     } else {
         releasable.release(); // [ts] Property 'release' does not exist on type 'number | Releasable'.
     }
}

Currently type guards are only limited to literals. Type guards are consumed at compile time and from this taken in mind variables defined with let or var seems natural to not result in proper control flow but type guards using constants defined with const should result in a proper type guard. Since the compiler already knows that consts will not change their value ans so their value should be checked dose it evaluate to known typeof return value to form a proper control flow else to result in a [ts] error ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    CommittedThe team has roadmapped this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions