Reputation: 503
I want to define a method in class that will have type based on argument supplied on constructor such as:
class A {
private model: any;
constructor(model: any) {
this.model = model;
}
getModel() {
return this.model;
}
}
class B {
hello() {
console.log("hi");
}
}
class C {
hi() {
console.log("hi");
}
}
const objA = new A(new B());
const objb = objA.getModel();
objb.hello();
Here the type of objb
is any
, which is the type of model
in class A, but I want it to be the type of class B
or any class object I pass into the A class constructor. How can I achieve this in TypeScript?
Upvotes: 0
Views: 92
Reputation: 1806
class A<Model> {
private model: Model;
constructor(model: Model) {
this.model = model;
}
getModel(): Model {
return this.model;
}
}
class B {
hello() {
console.log("hi");
}
}
class C {
hi() {
console.log("hi");
}
}
const objA = new A(new B());
const objb = objA.getModel();
objb.hello();
Upvotes: 1