In my current scenario, I am dealing with a set of types: X
, Y
, and Z
, all of which extend the same common interface J
. My goal is to define a method that looks like this:
class MyClass {
private someNumber = 1;
private someProperty;
addElement(cls: {new(number): J}) {
var element = new cls(this.someNumber);
element.performOperation(this.someProperty);
return element;
}
}
What I essentially need is a way to create an instance and associate it with specific data related to the creating instance.
This method would be called as follows:
var creator = new MyClass();
elementX = creator.addElement(X);
The above code works fine. However, TypeScript considers elementX
to be of type J
rather than reflecting the original type X
. I want to ensure that the type reflects X
while still restricting cls
to an implementation of J
. It may be challenging to achieve this level of specificity in TypeScript, even though technically possible.