Skip to content

unknown isn’t narrowed by assignmentΒ #43584

Open
@JonathanDCohen

Description

@JonathanDCohen

Bug Report

πŸ”Ž Search Terms

try block

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about try-catch blocks

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function f(request: {params: {[param: string]: unknown;}}) {
    let x = request.params.x;
    try {
        x = validate(x);
    } catch (e) {}

    try {
        takesString(x);  // Fails to compile, x is of type unknown.
    } catch (e) {}
}

function validate(x: unknown): string { return ""; }
function takesString(s: string) {}

πŸ™ Actual behavior

In this example, the code fails to compile because tsc has deduced x in the second block to be of type unknown

πŸ™‚ Expected behavior

Since we have successfully exited the first try-catch block, x's type should be narrowed to string in the second.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions