Skip to content

Can't narrow error type in catch clause #8677

Closed
@yortus

Description

@yortus
try {
    ...
}
catch (ex) { // Adding an annotation here gives ERROR TS1196: Catch clause variable cannot have a type annotation
    if (ex instanceof FooError) {
        ex; // ex is of type any
        ex.message; // OK
        ex.iDontExist; // typechecks OK, but doesn't exist
    }
    else if (isBarError(ex)) {
        ex; // ex is of type any
        ex.foo(); // typechecks OK, but runtime error
    }
    else {
        ...
    }
}

I guess this is expected behaviour not a bug. But I was not previously aware that the catch clasue variable cannot be annotated. Due to #1426, this means we can't narrow ex inside the catch clause, so all the cases dealing with specific error types get no type checking (since ex remains as any).

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA 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