我尝试创建一个泛型函数,该函数根据索引返回对象的值。索引将作为参数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();
}
}