Typescript refuses to narrow with a call to fail
but will narrow with a call to fail2
. Is this a bug in typescript?
const fail = (message?: string): never => {
throw new Error(message);
};
function fail2(message?: string): never {
throw new Error(message);
}
const getData = (): string | null => {
return "the-data";
}
export const loadDataOrError = (): string => {
const data = getData();
if (data === null) {
// Swap the below and see that it works
// fail2();
fail();
}
// This errors
return data;
};
here is a playground if you want to try switching the comments and seeing the error vanish.
fail
can be reassigned, the new value will still returnnever
so that's not a good reason. In your example you are usingas
which is unsound by design, so obviously you can get weird behavior. – Syringomyeliaconst
so the whole argument is unsound – Coverage