Whenever I have to work with objects that have a combined union type, typescript complains about the properties that I try to access and I don't get autocompletion either. For example this:
interface A {
id: string;
value: number;
}
interface B {
result: string;
}
export type Types = A | B;
function test(obj: Types) {
obj.result; // want to work with obj as though it implements interface B
}
I get errors when I access result
, id
, and value
from typescript:
Property 'result' does not exist on type 'Types'.
Property 'result' does not exist on type 'A'
Is there any way that I can narrow down the interface type so that I would get a better IDE experience?
result
only exists onB
, if yourobj
is aA
, then accessingresult
on it will returnundefined
– Cand