I have implemented a user-defined type guard to verify my object's type, as outlined here. While the example in the documentation works well when used alone, I encountered an issue when incorporating the typeguard within another 'check' function.
Below is a simple demonstration of the problem:
export interface A {
a: string;
}
export interface B extends A {
b: string;
c: string;
}
// check for properties b and c.
export const isB = (example: A | B): example is B => {
return (<B>example).b !== undefined && (<B>example).c !== undefined;
};
// check for properties b and c with c equaling 'foo'.
export const cEqualsFoo = (example: A | B): boolean => {
return isB(example) && example.c === "foo";
};
In my Vue2 component, I have a prop defined as follows and am utilizing my type guard methods:
x: {
type: Object as PropType<A> | PropType<B>
}
// later, in the method
if (isB(this.x)) {
// works!
console.log(this.x.b);
}
if (cEqualsFoo(this.x)) {
console.log(this.x.a);
console.log(this.x.b); // does not work - typescript throws "Property 'b' does not exist on type 'A'.
console.log(this.x.c); // does not work - typescript throws "Property 'c' does not exist on type 'A'.
}
Interestingly, the isB
function check succeeds, but the cEqualsFoo
function fails, triggering the TypeScript error mentioned above in the commented code section.
This discrepancy is puzzling since cEqualsFoo
leverages isB
function internally.
What is causing this issue and how can it be resolved?