基于类属性的泛型函数参数

时间:2020-05-24 07:23:32

标签: typescript generics typescript-generics

我尝试创建一个泛型函数,该函数根据索引返回对象的值。索引将作为参数name传递。该对象将从类的通用接口Properties定义,并扩展基本属性集DefaultPropertyInterface

代码完成正常,我只能将正确的索引传递给函数。但是在函数本身中,我遇到了错误。 ERROR: TS2536: Type 'K' cannot be used to index type 'PropertyListenerProperties<ComponentDataInterface>'.

我可以将propertyListeners转换为any,但这不是解决方案。我希望有人有一个更好的主意来解决我的问题。

这是我的简化代码:

type PropertyListenerProperties<T> = {
  [P in keyof (T & DefaultPropertyInterface)]?: Subject<(T & DefaultPropertyInterface)[P]>
}

type DefaultPropertyInterface = {
  name: string;
}

export abstract class MyAbstractClass<Properties> {

  private propertyListeners: PropertyListenerProperties<Properties> = {};

  public propertyChanged<T extends PropertyListenerProperties<Properties>, K extends keyof T>(name: K): Observable<T[K]> {

    //
    // ERROR: TS2536: Type 'K' cannot be used to index type 'PropertyListenerProperties<Properties>'.
    //
    if (!(this.propertyListeners)[name]) {
      (this.propertyListeners)[name] = new Subject<T[K]>();
    }

    return (this.propertyListeners)[name].asObservable();
  }
}

0 个答案:

没有答案