【问题标题】:Factory method on base class to instantiate derived classes基类上的工厂方法实例化派生类
【发布时间】:2016-11-14 01:07:27
【问题描述】:

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

  • 尽管有 ///<reference>,但我收到 TS 警告(请参阅代码):“typeof MyNS”类型上不存在属性“Base”
  • 有充足的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

将后代类公开给基类的更好方法是什么?

【问题讨论】:

    标签: typescript


    【解决方案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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 2016-07-06
      • 1970-01-01
      • 2018-11-03
      • 2023-02-03
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      相关资源
      最近更新 更多