Skip to content

Allow switch type guards #2214

Closed
Closed
@icholy

Description

@icholy

I have the following code:

function logNumber(v: number) { console.log("number:", v); }
function logString(v: string) { console.log("string:", v); }

function foo1(v: number|string) {
    switch (typeof v) {
        case 'number':
            logNumber(v);
            break;
        case 'string':
            logString(v);
            break;
        default:
            throw new Error("unsupported type");
    }
}

Error:

Argument of type 'string | number' is not assignable to parameter of type 'number'.
 Type 'string' is not assignable to type 'number'.

I was forced to rewrite this using if statements.

function foo2(v: number|string) {
    if (typeof v === 'number') {
        logNumber(v);
    } else if (typeof v === 'string') {
        logString(v);
    } else {
        throw new Error("unsupported type");
    }
}

Please allow using switch statements as type guards.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Effort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Help WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions