2017-01-30 7 views
0

型(型のインスタンスではなく)をパラメータとして渡したいと思っていますが、型を特定の基本型に拡張する必要がある規則を適用したいType型でインスタンスではなく型にチェックする

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

は、2つのオプションがあります。

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 
あなたはたとえば、プロパティを追加した場合
関連する問題