Reputation: 727
In alpha
I check whether the result is null
and throw new Error
if so, but the comiler still shows 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);
}
But this code works perfectly well:
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);
}
Upvotes: 0
Views: 44
Reputation: 617
Typescript cannot prove that your objMethod
will always return the same value. It could return a non-null value at the first call, and null at the second. If you assign it to a const variable, the check asserts that the variable is not null. Since the variable is const, the value cannot change after the assignment, thus, it must be non-null if it passed the check.
Upvotes: 1