Consider the following:
class A {
commonString: string = "common";
}
class B extends A {
bString: string = "b";
}
class C extends A {
cString: string = "c";
}
It seems to me like a perfectly ordinary example of inheritance - one of the most basic, in fact. And yet, if I'm reading this documentation right, TypeScript's inheritance mechanism does not support this pattern? Consider the following two sources:
https://www.javatpoint.com/typescript-inheritance - "When more than one subclass is inherited from a single base class, then this type of inheritance is known as hierarchical inheritance. ... TypeScript does not support hierarchical inheritance."
https://www.w3spoint.com/inheritance-typescript - after listing the five types of inheritance the other article listed, says "TypeScript only support Single and Multilevel Inheritance."
I find this difficult to believe, for two reasons:
- It's nonsense. Combining common fields and methods is basically THE REASON you use classes. If all you need is to ensure adherence to a contract, just use interfaces.
- It appears to be false? The example code above is code I wrote into a typescript file, and it seems to work fine. b: B = B() behaves as expected: if I access b.bString it's fine, if I access b.cString it errors, if I store b: A = new B(), it works but compile-errors if I access b.bString (but at runtime bString is in fact present). It behaves exactly as I'd expect.
So, what's going on here? Have I misunderstood "hierarchical inheritance"? Are the given articles wrong? Does typescript claim not to support it, but really it does? Has my compiler been blessed by gnomes?
More to the point, can I trust the usual "B extends A, and also C extends A" to continue to work as expected?