【问题标题】:Collect only keys for values of a certain type from a collection仅从集合中收集特定类型值的键
【发布时间】:2019-12-10 05:24:01
【问题描述】:

例如,假设我们有

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的一种方式吗?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

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

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

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

    对于您的情况,此中间类型如下所示:

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

    然后,该中间类型再次由 T 的键索引。这将产生您想要的联合,因为此处的编译器会忽略 never 类型。

    Playground

    【讨论】:

      猜你喜欢
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      相关资源
      最近更新 更多