2017-01-30 92 views
0

我想能够传递一个类型(而不是类型的一个实例)作为参数,但我想执行一个规则,其中类型必须扩展一个特定的基类型TypeScript类型检查类型而不是实例

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的东西...别的吗?

这是可能的TypeScript?

注意:TypeScript也应该认识到shape有一个默认构造函数。在C#中,我会做这样的事情...

class ShapeMangler 
{ 
    public void Mangle<T>() where T : new(), Shape 
    { 
     Shape shape = Activator.CreateInstance<T>(); 
     // mangle the shape 
    } 
} 

回答

1

有两种选择:

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 
相关问题