Here's a straightforward example.
type Callback<T> = (sender: T) => void;
class Warehouse<T> {
private callbacks: Callback<T>[];
public constructor(callbacks: Callback<T>[]) {
this.callbacks = callbacks;
}
// Tasks in the warehouse are executed.
public update(sender: T): void {
for (const callback of this.callbacks) {
callback(sender);
}
}
}
class Item {
public warehouse: Warehouse<Item>;
public constructor(...callback: Callback<Item>[]) {
this.warehouse = new Warehouse(callback);
}
public process(): void {
this.warehouse.update(this);
}
public checkStock(): void {}
}
class Product extends Item {
public override warehouse: Warehouse<Product>;
public constructor(...callback: Callback<Product>[]) {
super(callback);
this.warehouse = new Warehouse(callback);
}
public deliverOrder(): void {};
}
new Item((sender) => {
sender.checkStock();
});
new Product((sender) => {
sender.deliverOrder();
});
I'm confused about the issue at hand here. Car is derived from Vehicle.
Is there something I'm overlooking, or is it a limitation with generic classes and TypeScript's ability to validate them accurately?
What might be an alternative solution where you pass the appropriate class to the callback and TypeScript interprets it correctly?