Given the following interfaces and type:
interface A {
foo: string;
}
interface B {
bar: string;
}
type AorB = A | B;
The following works:
function getFooOrBar(obj: AorB): string {
if ('foo' in obj) {
return obj.foo;
}
return obj.bar
}
But the following won't:
function getFooOrBar(obj: AorB): string {
if (isA(obj)) {
return obj.foo;
}
return obj.bar;
}
function isA(obj: AorB): boolean{
return 'foo' in obj;
}
because I guess the compiler is not smart enough to infer the property's existence based on the implementation of a function.
Is there a way to extract 'foo' in obj
into a helper function so the compiler can still infer the existence of obj.foo
?
CodePudding user response:
You need to use typeguards:
interface A {
foo: string;
}
interface B {
bar: string;
}
type AorB = A | B;
function isA(obj: AorB): obj is A { // change is here
return 'foo' in obj;
}
function getFooOrBar2(obj: AorB): string {
if (isA(obj)) {
return obj.foo; // ok
}
return obj.bar; // ok
}