I have the following code:
interface A {
a: number;
}
interface B extends A {
b: number;
}
const instanceOfB: B = {
a: 1,
b: 2,
}
const myFunct = (arg: A | B) => {
const myNumber = arg.b ?? 42;
console.log(myNumber);
};
myFunct(instanceOfB);
Inside myFunct
I want to access the b
property of arg
, which might or might not exist on arg
depending on whether or not arg
is of type B
. In case it does not exist and the access returns undefined
, I use the fallback value of 42
.
Typescript complains that Property 'b' does not exist on type 'A | B'.
, which is true. A | B
is basically the same as A
since only a
is shared between them both, yet I would still like to try to access it and use my fallback value if it doesn't.
I know I could change my JavaScript to satisfy Typescript by changing the relevant line to e.g. const myNumber = "b" in arg ? arg.b : 42;
, but I really don't want to change my JavaScript code just to make Typescript happy when my code is (in my opinion) perfectly fine.
Is there a Typescript only solution to my Typescript only problem?
Also, if someone knows, I would be very interested in why Typescript complains about arg.b ?? 42
but not "b" in arg ? arg.b : 42
.