Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch on unknown should narrow like if #29710

Closed
jack-williams opened this issue Feb 3, 2019 · 1 comment
Closed

Switch on unknown should narrow like if #29710

jack-williams opened this issue Feb 3, 2019 · 1 comment
Labels
Experience Enhancement Noncontroversial enhancements Suggestion An idea for TypeScript

Comments

@jack-williams
Copy link
Collaborator

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms: switch narrow unknown if

I realised that the most compelling use-case of narrowing unknown by === is for a selection of strings/enums, but IMO, this is cleaner when written as a switch.

Code

enum SomeResponse {
    Yes,
    No,
    Maybe,
}

function foo(x: unknown): SomeResponse {
    switch (x) {
        case SomeResponse.Yes:
        case SomeResponse.No:
        case SomeResponse.Maybe:
            return x;
        default:
            throw new Error("I don't know. Can you repeat the question?");
    }
}

Expected behavior:
No error.

Actual behavior:
Error on return statement: unknown is not assignable to SomeResponse

Playground Link: playground

Related Issues: #25720 #25172

@jack-williams
Copy link
Collaborator Author

Fix here #29711

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript Experience Enhancement Noncontroversial enhancements labels Feb 5, 2019
RyanCavanaugh added a commit that referenced this issue Feb 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Experience Enhancement Noncontroversial enhancements Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants