I have a class that looks like this:
export class Layer
{
public raster: BaseRaster;
constructor(raster: BaseRaster)
{
this.raster = raster;
}
}
In my project, I also have an abstract class named BaseRaster
export abstract class BaseRaster
{
public doBasicStuff(): void { ... }
}
Within my project, there are multiple classes that extend the BaseRaster class. For example:
export class ValueRaster extends BaseRaster
{
public doMoreStuff(): void { ... }
}
export class ZoneRaster extends BaseRaster
{
public doMoreStuff(): void { ... }
}
The problem arises when I try to call a method from one of these extended classes on the Layer's raster property:
let valueRaster = new ValueRaster();
let layer = new Layer(valueRaster);
layer.raster.doMoreStuff(); // This line fails!
This is because Typescript considers layer.raster as type BaseRaster, not the specific extended class.
To work around this issue, I've had to implement type checks:
if (layer.raster.constructor.name === 'ValueRaster')
{
(layer.raster as ValueRaster).doMoreStuff();
}
else if (layer.raster.constructor.name === 'ZoneRaster')
{
(layer.raster as ZoneRaster).doMoreStuff();
}
While this solution works, it feels awkward and cumbersome.
Is there a way to achieve proper polymorphism in Typescript? In languages like Java, C++, or C#, calling layer.raster.doMoreStuff() would work seamlessly without the need for such type checks.