基类上的工厂方法,用于实例化派生类

时间:2016-07-11 23:44:56

标签: typescript

我试图在我的基类上有一个通用工厂方法,可以实例化任何后代类,而基类不知道所有后代是什么。以下产生了工作JS,但是......

  • 尽管///<reference>我收到了TS警告(见代码):Property&#39; Base&#39; MyNS&#39;
  • 的类型&#39;类型不存在
  • 有足够的warnings in the Typescript docs about wrapping modules in namespaces
  • 这种方法似乎只有在文件被绑定到单个outFile时才会起作用,因为类绑定到exports的方式(参见底部的要点)。这是可以接受的,但如果有一种方法没有这种限制,我很好奇。

Base.ts:

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

Descendant.ts:

/// <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;
        }
    }
}

结果JS:https://gist.github.com/zbjornson/2053cf1a30e893f38f7910dcada712d2

什么是将后代类暴露给基础的更好方法?

1 个答案:

答案 0 :(得分:2)

(我提出了一个答案,但仍然非常欢迎任何其他解决方案。)

一种方法是使用装饰器:

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