2017-01-30 101 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 
相關問題