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
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…