Imagine I have a combination of classes:
type X = ClassA | ClassB | ClassC;
Both ClassA and ClassC have a shared method called methodY
.
Why is it that I can't simply use the optional chaining operator to call for methodY?
class ClassA {
methodY() {
return 'a';
}
}
class ClassB {}
class ClassC {
methodY() {
return 'c';
}
}
type X = ClassA | ClassB | ClassC;
function getMethodY(x: X) {
return x.methodY?.(); // Error: Property 'methodY' does not exist on type 'ClassB'.
}
Instead, I find myself having to use these patterns:
methodY in doc && doc.methodY()
or if (methodY in doc) doc.methodY()
, which seem very similar to the optional chaining operator. Why is there a difference between checking for methodY in doc
versus using the operator directly?
What design reasons justify why the check for methodY in doc
should be treated differently than using the operator itself?