2012-11-27 2 views
2

예제 코드 형식 '기능'의
값을 newable되지 않습니다 : 예제의생성자에 대한 참조를 어떻게 저장합니까? 문제가되는 행동을 보여주는

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) (... 새 반환) 그 불평을 컴파일러가 .

나중에 임의의 클래스의 생성자를 변수에 저장하여 나중에 인스턴스화 할 수있는 적절한 방법은 무엇입니까?

답변

6

유형 리터럴을 사용하여 new'd가 될 수있는 객체를 지정할 수 있습니다.

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 
이 너무 추가 형 안전의 장점을 가지고 있습니다
관련 문제