Reputation: 4615
Say I have a base class and a number of derived classes. Is there a way to annotate the inherited members without having to re-implement them in the derived classes?
Consider something like this:
class BaseModel {
collection: Collection;
constructor(collectionName: string) {
this.collection = connectToCollection(collectionName);
}
create(data: {}) { // <- I would like to annotate 'data' in the derived classes
this.collection.insert(data);
}
}
class ModelA extends BaseModel {
constructor(collectionName: string) {
super(collectionName);
}
}
class ModelB extends BaseModel {
constructor(collectionName: string) {
super(collectionName);
}
}
The argument for the create
member is different for ModelA and ModelB, so I would like to annotate them separately.
I guess I can re-implement them like this:
class ModelA extends BaseModel {
constructor(collectionName: string) {
super(collectionName);
}
create(data: ArgsForModelA) {
this.super.create(data);
}
}
class ModelB extends BaseModel {
constructor(collectionName: string) {
super(collectionName);
}
create(data: ArgsForModelB) {
this.super.create(data);
}
}
But it just does not feel right, so I am curious to if it's possible to annotate the inherited members without re-implementing each one of them in all the derived classes (phew).
Upvotes: 0
Views: 168
Reputation: 2242
You can use generics for this.
class BaseModel<T> {
collection: Collection;
constructor(collectionName: string) {
this.collection = connectToCollection(collectionName);
}
create(data: T) {
this.collection.insert(data);
}
}
class ModelA extends BaseModel<ArgsForModelA> {
constructor(collectionName: string) {
super(collectionName);
}
}
class ModelB extends BaseModel<ArgsForModelB> {
constructor(collectionName: string) {
super(collectionName);
}
}
Upvotes: 3