我有一个包含两个泛型数组的泛型抽象类:
export abstract class DataProvider<V, T extends {token:string}> {
inputA: T[] = [];
result: V[] = [];
}
我想提供一个函数,您可以在其中传递一个属性名称,该名称应该出现在T
和V
中(并且以某种方式也应该具有正确的类型).
然后,该函数应该在两个数组中找到具有该属性名和相同值的项,并检索令牌并返回一条消息.
这就是我得到的结果:
public generateMessagesByAttribute<K extends keyof V & keyof T>(attributeName: K): SuccessMessage[] {
const successMessages: SuccessMessage[] = [];
this.result.forEach(item => {
const index = this.inputA.findIndex(input => input[attributeName] === item[attributeName]); // here is the error
if (index !== -1) {
successMessages.push({
taskToken: this.inputA[index].token,
output: JSON.stringify(item),
});
}
});
return successMessages;
}
但是,我收到此错误:
The comparison appears to be unintentional because because the types U[K] and V[K] have no overlaps
个
这是我不明白的,因为我清楚地说明了K extends keyof U & keyof V
.
此外,这看起来不是很安全,因为即使属性名可以出现在两个数组中,它们也可以有不同的类型.我怎么才能把这件事也插手呢?
[更新]一个建议的解决方案是将inputA
的类型扩展到(T&V)[]
.然而,这意味着inputA
将包含T
和V
的所有props ,这不是我想要的.然而,我可以以某种方式使inputA
的类型更具体,在这个意义上,它必须有一个属性,必须在T
和V
.
但是我不确定当这个属性在类的构造函数中传递时,因此在运行时,这是否可能.