从集合中仅收集特定类型值的键 [英] Collect only keys for values of a certain type from a collection

查看:26
本文介绍了从集合中仅收集特定类型值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如假设我们有

type AnObject = {
  a: string
  b: number
  c: string
  d: number
}

type ExtractKeysOfType<O extends {[K: string]: any}, T> = ///...

type StringKeys = ExtractKeysOfType<AnObject, string> // 'a' | 'c'

它们是实现 ExtractKeysOfType 的方法吗?

Is they're a way to achieve ExtractKeysOfType ?

推荐答案

您可以在此处结合使用映射类型和条件类型:

You can use mapped types combined with conditional types here:

type ExtractKeysOfType<T, Target> = {
  [K in keyof T]: T[K] extends Target ? K : never
}[keyof T];

这基本上是通过遍历 T 类型中的每个键来工作的.T[K] 是否扩展了我们的 Target 类型?如果是这样,那就太好了,并且属性值就是那个 Key.如果不是,则该键的类型为 never.

This essentially works by going over each key in type T. Does T[K] extend our Target type? if so, great, and the property value is simply that Key. If not, that key has type never.

对于您的情况,这种中介类型如下所示:

This intermediary type, for your case, looks like:

{
    a: "a";
    b: never;
    c: "c";
    d: never;
}

然后,该中间类型被 T 的键再次索引.这将产生您想要的联合,因为 never 类型在这里被编译器忽略.

Then, that intermediary type is indexed again by keys of T. This will produce your desired union, since the never types are ignored by the compiler here.

游乐场

这篇关于从集合中仅收集特定类型值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆