简体   繁体   English

我可以使用 Typescript generics 过滤来自 object 的密钥吗?

[英]Can I use Typescript generics to filter keys from an object?

I have a filter function with working logic, but I don't know how to write its types:我有一个带有工作逻辑的过滤器 function,但我不知道如何编写它的类型:

export function filter<T>(object: T, ...keys: Array<keyof T>): ??? {
  let index = -1;
  const length = keys.length;
  const result = { ...object };

  while (++index < length) {
    const key = keys[index];
    if (key in object) delete result[key];
  }
  return result;
}

filter({ a: 1, b: 2 }, 'b')  // { a: 1 }

Typescript still think 'b' property exists, so I'm looking for a way to specify that keys get removed from T . Typescript 仍然认为 'b' 属性存在,所以我正在寻找一种方法来指定从T中删除keys

I'm familiar with Omit (but generally pretty new to Typescript), and I think it could play a role in this, but I haven't come up with a way to make it and the Array meet...我对Omit很熟悉(但对 Typescript 来说通常很新),我认为它可以在这方面发挥作用,但我还没有想出办法让它和Array相遇......

Does someone see the path I'm looking for?有人看到我正在寻找的路径吗?

(btw the specific signature of filter isn't important, if you have an alternative implementation that's more conducive to type-safety I'm happy to hear it) (顺便说一句, filter的特定签名并不重要,如果您有一个更有助于类型安全的替代实现,我很高兴听到它)

The solution is to extract keyof T into a generic.解决方案是将keyof T提取到泛型中。 This should work:这应该有效:

export function filter<T, K extends keyof T>(object: T, ...keys: Array<K>): Omit<T, K> {
  let index = -1;
  const length = keys.length;
  const result = { ...object };

  while (++index < length) {
    const key = keys[index];
    if (key in object) delete result[key];
  }
  return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM