[英]TypeScript type checking on type rather than instance
我希望能够传递一个类型(而不是该类型的实例)作为参数,但是我想强制执行一个规则,其中该类型必须扩展特定的基本类型
例
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.
从本质上讲,我认为我需要替换shape: Function
用其他东西代替shape: Function
?
TypeScript可以实现吗?
注意:TypeScript还应该识别shape
具有默认构造函数。 在C#中,我会做这样的事情...
class ShapeMangler
{
public void Mangle<T>() where T : new(), Shape
{
Shape shape = Activator.CreateInstance<T>();
// mangle the shape
}
}
有两种选择:
class ShapeMangler {
public mangle<T extends typeof Shape>(shape: T): void {
// mangle the shape
}
}
要么
class ShapeMangler {
public mangle<T extends Shape>(shape: { new(): T }): void {
// mangle the shape
}
}
但是这两种方法对于编译器都可以:
mangler.mangle(Circle);
mangler.mangle(NotAShape);
在您发布的示例中,因为您的类为空,并且空对象与结构中的所有其他对象匹配。
如果添加属性,例如:
abstract class Shape {
dummy: number;
}
然后:
mangler.mangle(NotAShape); // Error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.