Closed
Description
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.