使类扩展某些类型的泛型类,而无需使用装饰器为其重新提供

时间:2019-10-22 17:03:06

标签: typescript typescript-typings typescript-generics typescript3.0

我想让一个类扩展具有特定泛型类型的另一个类,其中该类型由装饰器提供。我想从装饰器传递类型,以在抽象类MutatorBase中使用。我不能只跳过装饰器而仅扩展抽象类的原因是因为我需要获取所提供的类/类型的构造函数。

这是我要实现的目标:

type Constructor<T> = new (...args: any[]) => T;
type ObjectTuple = readonly Constructor<unknown>[];

function Mutator<T extends ObjectTuple>(...objs: T) {
    return <U extends MutatorBase<T>>(mutator: U) => {
      // do meta stuff
  };
}

abstract class MutatorBase<T extends ObjectTuple = []> {
    mutate(fn: (objs: T) => void) {
        // get objects
        // call fn(objs);
    }
}

class ObjectExample {
    data: number = 0;
}

@Mutator(ObjectExample)
class MutatorExample extends MutatorBase {

}

这不起作用,因为即使类扩展了mutate,装饰器也找不到函数MutatorBase。同样,装饰器中提供的类型也可能不会转移。

现在MutatorExample extends MutatorBase<[typeof ObjectExample]>将解决此问题,但要求我第二次提供这些对象,这是我要避免的事情。

这有可能吗?

0 个答案:

没有答案
相关问题