What causes the discrepancy in outcomes when inferring the never
return type in the following TypeScript code (Version 4.3.2 or 4.4.0-nightly)? See comments in the code snippet below:
const willThrowException: (message: string) => never = (message) => {
throw new Error(message);
}
try {
willThrowException('some message');
willThrowException('another message'); // OK: compiler will error 'Unreachable code detected'
} catch(e) {}
const willThrowExceptionToo = (message: string): never => {
throw new Error(message);
}
try {
willThrowExceptionToo('some message');
willThrowExceptionToo('another message'); // NOT OK: compiler will not error
} catch(e) {}
The autocomplete feature in the TypeScript compiler recognizes that the function has a return type of never
:
https://i.sstatic.net/mfXFB.png
However, the execution flow is not blocked in the same way as indicated by the declared type, which is more explicit but aligns better with best practices.