I am dealing with an abstract base type and multiple subtypes of it, some of which are abstract on their own and have further subtypes.
My goal is to define polymorphic functions in TypeScript, where some may be abstract while others have default implementations that can be overloaded by specific instances.
How can I best represent this model in TypeScript?
In JavaScript, I typically use classes. Below is a simple example to illustrate what my code might look like. Please focus on the data structure rather than the semantics.
// Code example
However, translating this code directly into TypeScript poses challenges:
The field
name
cannot serve as a discriminant forPolygon
. A proper discriminant would require introducing a new typePolygonType = Triangle | Square;
and usingPolygonType
instead ofPolygon
for unknown subtypes.Using classes limits expressiveness, hindering possibilities such as type level metaprogramming to define precise types.
An alternative approach in TypeScript could involve modeling types using type
s but sacrificing prototype inheritance polymorphism.
I am curious about other solutions to this common problem and whether one is generally preferred over others.