【问题标题】:How to intersect two classes as base class for extended class in Typescript如何在 Typescript 中将两个类作为扩展类的基类相交
【发布时间】:2019-08-15 15:08:41
【问题描述】:

我需要创建 HOF(高阶函数),它将修改/添加属性到提供的类的原型。有可能吗?

interface IStore {
  new (): {};
}

interface IWatchable {
  new() : {
    watch: boolean;
  };
}

const Store = <T extends IStore>(clazz: T): T & IWatchable => {
  return class extends clazz {
    watch = true;
  };
};

 class X extends Store(class {})
//              ^^^^^^^^^^^^^^ 
//              Base constructors must all have the same return type.

【问题讨论】:

    标签: typescript types constructor casting extends


    【解决方案1】:

    如果你想做混入,这是可行的模式(根据this PR):

    interface IStore {
        new(...a: any[]): {}; 
    }
    
    const Store = <T extends IStore>(clazz: T) => {
        return class extends clazz {
            watch = true;
        };
    };
    
    class X extends Store(class { }) { }
    

    这应该给你你想要的,你可以拥有IWatchable接口,即使Store函数的返回没有显式实现接口,mixin类也可以分配给它(结构类型的奇迹)

    interface IWatchable {
        new(): {
            watch: boolean;
        };
    }
    let w : IWatchable = X //ok
    

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 2019-09-16
      • 2016-10-21
      • 2013-04-27
      • 2013-06-18
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多