jdsmith2816
jdsmith2816

Reputation: 325

How do I store a reference to a constructor?

Example code demonstrating the behavior in question:

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();
        }
    }
}

Line 17 of the example (return new......) causes the compiler to complain that:
Value of type 'Function' is not newable.

What is the proper way to store the constructor of any arbitrary class in a variable so that I can later instantiate it.

Upvotes: 3

Views: 1319

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221282

You can use a type literal to specify an object that can be new'd. This has the advantage of added type safety, too:

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

Upvotes: 7

Related Questions