2016-07-11 4 views
0

모든 하위 클래스가 무엇인지 알고있는 기본 클래스없이 자손 클래스를 인스턴스화 할 수있는 기본 클래스에 제네릭 팩터 리 메서드가 있어야합니다. 다음은 내가 TS가 (코드 참조) 경고 얻을 ///<reference>가 있더라도 ...파생 클래스를 인스턴스화하는 기본 클래스의 팩토리 메서드

  • JS 작업 만 낸다 : 부동산의 '베이스'유형에 존재하지 않는 '대해서 typeof MyNS'
  • 충분한있다
  • warnings in the Typescript docs about wrapping modules in namespaces .
  • 이 접근법은 클래스가 exports (아래의 gist 참조)에 바인딩되는 방식으로 파일이 단일 outFile로 연결되는 경우에만 작동하는 것으로 보입니다. 그것은 받아 들일 수 있지만,이 제한이없는 방법이 있다면 나는 궁금하다.

Base.ts : JS를 결과

/// <reference path="Base.ts" /> 
export namespace MyNS { 
    // Property 'Base' does not exist on type 'typeof MyNS': 
    export class Descendant extends MyNS.Base { 
     echo(s: string) { 
      return s; 
     } 
    } 
} 

:

export namespace MyNS { 
    export abstract class Base { 
     static create(foo) { 
      return new MyNS[foo.type](); 
     } 
    } 
} 

Descendant.ts에 자손 클래스를 노출 할 수있는 더 좋은 방법이 무엇 https://gist.github.com/zbjornson/2053cf1a30e893f38f7910dcada712d2

베이스?

답변

1

(. 다른 솔루션을 매우 환영 아직도 내가 생각 해낸 하나의 대답을 게시,하지만)

한 가지 방법은 데코레이터입니다 :

Base.ts :

var descendants = {}; 
export abstract class Base { 
    static create(foo) { 
     return new descendants[foo.type](foo); 
    } 

    static Descendant(constructor: Function) { 
     descendants[constructor.name] = constructor; 
    } 
} 

Descendant.ts :

import { Base } from "./Base.ts"; 

@Base.Descendant 
export class Descendant extends Base { 
    echo(s: string) { 
     return s; 
    } 
} 
관련 문제