Why does Typescript fail 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.
Screenshots for clarity
With an error
https://i.sstatic.net/ep9Z4.png