When checking for null in alpha
, I validate the result and use throw new Error
if needed. However, even after doing so, the compiler still indicates a compilation error:
const obj = {
objMethod: function (): string | null {
return 'always a string';
},
};
function alpha() {
if (obj.objMethod() === null) {
throw new Error('type guard, but compiler does not count it as one :( ');
}
const beta: string = obj.objMethod();
console.log(beta);
}
Surprisingly, the following code works without any issues:
const obj = {
objMethod: function (): string | null {
return 'always a string';
},
};
function alpha() {
const result = obj.objMethod();
if (result === null) {
throw new Error('this DOES count as a type guard. ');
}
const beta: string = result; // no error
console.log(beta);
}