Skip to content

Need to return value in a "never" path #13154

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

Closed
dingfengquek opened this issue Dec 24, 2016 · 2 comments
Closed

Need to return value in a "never" path #13154

dingfengquek opened this issue Dec 24, 2016 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@dingfengquek
Copy link

TypeScript Version: 2.1.4

Code

type X = string | number;
function isString1(x: X): boolean {
    if      (typeof x === 'string') { return true ; }
    else if (typeof x === 'number') { return false; }
    else {
        x; // Is of never type
        return false; // However, need a return to compile
    }
}
function isString2(x: X): boolean {
    if      (typeof x === 'string') { return true ; }
    else if (typeof x === 'number') { return false; }
    else { // x is of never type here
        ((a:never)=>{})(x); // Validate
        return false; // However, need a return to compile        
    }
}
function isString3(x: X): boolean {
    if      (typeof x === 'string') { return true ; }
    else if (typeof x === 'number') { return false; }
    else { // x is of never type here
        ((a:never)=>{ throw new Error();})(x); // Validate
        // Does not need a return to compile, is good
    }
}
const compileTimeAssertNever = (x:never) => { throw new Error('unreachable'); };
function isString4(x: X): boolean {
    if      (typeof x === 'string') { return true ; }
    else if (typeof x === 'number') { return false; }
    else { // x is of never type here
        compileTimeAssertNever(x); // Validate
        return false; // However, need a return to compile
        // Shouldn't this be like isString3?
        // It would be nice if it was
    }
}

It would be even better if an error doesn't need to be thrown, since once "x" is known to be type "never", the code block can never be reached.

@dingfengquek dingfengquek changed the title Need to return value in a "never" Need to return value in a "never" path Dec 24, 2016
@zpdDG4gta8XKpMCd
Copy link

Just do this, it will work:

return compileTimeAsserNever (x);

@mhegazy
Copy link
Contributor

mhegazy commented Dec 26, 2016

Please see #10470

@mhegazy mhegazy added the Duplicate An existing issue was already created label Dec 26, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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

4 participants