typescript - Hur sparar jag en referens till en konstruktor?


Exempelkod som visar det aktuella beteendet:

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

Rad 17 i exemplet (return new......) får kompilatorn att klaga på att:
Värdet av typen 'Function' kan inte instansieras.

Vad är det rätta sättet att lagra konstruktorn för en godtycklig klass i en variabel så att jag senare kan instansiera den.

Svar #1

Du kan använda en typ-literal för att specificera ett objekt som kan new'as. Detta har också fördelen av ökad typ-säkerhet:

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

Relaterade artiklar