Reputation: 42239
I want to be able to pass a type (rather than an instance of the type) as a parameter, but I want to enforce a rule where the type must extend a particular base type
Example
abstract class Shape {
}
class Circle extends Shape {
}
class Rectangle extends Shape {
}
class NotAShape {
}
class ShapeMangler {
public mangle(shape: Function): void {
var _shape = new shape();
// mangle the shape
}
}
var mangler = new ShapeMangler();
mangler.mangle(Circle); // should be allowed.
mangler.mangle(NotAShape); // should not be allowed.
Essentially I think I need to replace shape: Function
with something...else?
Is this possible with TypeScript?
Note: TypeScript should also recognise that shape
has a default constructor. In C# I would do something like this...
class ShapeMangler
{
public void Mangle<T>() where T : new(), Shape
{
Shape shape = Activator.CreateInstance<T>();
// mangle the shape
}
}
Upvotes: 0
Views: 195
Reputation: 164139
There are two options:
class ShapeMangler {
public mangle<T extends typeof Shape>(shape: T): void {
// mangle the shape
}
}
Or
class ShapeMangler {
public mangle<T extends Shape>(shape: { new(): T }): void {
// mangle the shape
}
}
But both of these will be fine with the compiler:
mangler.mangle(Circle);
mangler.mangle(NotAShape);
With the example you posted because your classes are empty, and an empty object matches every other object in structure.
If you add a property, for example:
abstract class Shape {
dummy: number;
}
Then:
mangler.mangle(NotAShape); // Error
Upvotes: 1