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 (true) cannot be used to implement type guards #16653

Closed
kujon opened this issue Jun 20, 2017 · 1 comment
Closed

switch (true) cannot be used to implement type guards #16653

kujon opened this issue Jun 20, 2017 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@kujon
Copy link
Contributor

kujon commented Jun 20, 2017

TypeScript Version: 2.4.0

Code

// Compiles
const typeGuardsOne = (value: number | string | Date): string => {
    if (typeof value === 'number') {
        return value.toFixed(0);
    } else if (value instanceof Date) {
        return value.getTime().toString();
    } else if (typeof value === 'string') {
        return value;
    }
};

const typeGuardsTwo = (value: number | string | Date): string => {
    switch (true) { 
        case typeof value === 'number':
            // Property 'toFixed' does not exist on type 'string | number | Date'.
            return value.toFixed(0);
        case value instanceof Date:
            // Property 'getTime' does not exist on type 'string | number | Date'.
            return value.getTime().toString();
        case typeof value === 'string':
            // Type 'string | number | Date' is not assignable to type 'string'.
            return value;
    }
};

Expected behavior:
I personally find the switch (true) trick to be a really readable and concise way of implementing type guards/pattern matching (especially if a few cases need to be treated in the same way). Typescript doesn't seem to evaluate the cases and the typeGuardsTwo example doesn't compile. It treats the value inside of each case as if it still was number | string | Date.

Actual behaviour
The code doesn't compile with the errors listed in the Code section.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jun 20, 2017
@RyanCavanaugh
Copy link
Member

See #8934

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants