迭代对象的通用属性,验证它是对象的 属性 而不是任何字符串(我从编译器收到错误)

Iterate over generic properties of an object validating that is a property of the object and not any string (I receive an error from the compiler)

valuesOrCondition$<T>(objects: Observable<T[]>, objectWithPropertiesAndValues: Partial<T>) {

  const properties = Object.keys(objectWithPropertiesAndValues);
  return objects.pipe(  
      map(nodes => nodes.filter(node => 
                                   properties.find(ppName => 
                                   node[ppName] === objectWithPropertiesAndValues[ppName]))),
  );

}

当我执行这段代码时,TypeScript 给我这个错误:

元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'unknown'。在 'unknown'.

类型上未找到参数类型为 'string' 的索引签名

但是 objectWithPropertiesAndValuesPartial<T> 这意味着 node 总是存在于 T.

我明白这个问题,我知道我只需添加 any 就可以了。但我想在这里尊重 Typescript 的方式。

Typescript 有时需要开发人员确定,这就是为什么您有时使用 .?!. 在这种情况下您需要指定结果是 [keyof Partial<T>][keyof T].为了保持一致性,使用第一个。

替换此行:

const properties = Object.keys(objectWithPropertiesAndValues);

对于这个:

const properties = Object.keys(objectWithPropertiesAndValues) as [keyof Partial<T>];