3

問題の動作を示すサンプルコード:

export class NodePool {
    private tail: Node;
    private nodeClass: Function;
    private cacheTail: Node;

    constructor(nodeClass: Function) {
        this.nodeClass = nodeClass;
    }

    get(): Node {
        if (this.tail) {
            var node = this.tail;
            this.tail = this.tail.previous;
            node.previous = null;
            return node;
        } else {
            return new this.nodeClass();
        }
    }
}

例の17行目(return new ......)により、コンパイラーは次のように文句を言い
ます。タイプ'Function'の値はnewableではありません。

後でインスタンス化できるように、任意のクラスのコンストラクターを変数に格納する適切な方法は何ですか。

4

1 に答える 1

7

タイプリテラルを使用して、新規作成できるオブジェクトを指定できます。これには、タイプの安全性が追加されるという利点もあります。

export class NodePool {
    private tail: Node;
    private cacheTail: Node;

    constructor(private nodeClass: { new(): Node; }) {
    }

    get(): Node {
        if (this.tail) {
            var node = this.tail;
            this.tail = this.tail.previous;
            node.previous = null;
            return node;
        } else {
            return new this.nodeClass();
        }
    }
}

class MyNode implements Node {
    next: MyNode;
    previous: MyNode;
}

class NotANode {
    count: number;  
}

var p1 = new NodePool(MyNode);   // OK
var p2 = new NodePool(NotANode); // Not OK
于 2012-11-27T22:59:59.047 に答える