首页 > 解决方案 > 值扩展 V 的键

问题描述

例如:

interface Foo {
  a: string
  b: string
  c: number
}

我如何定义KeysOf<T, V>这样的KeysOf<Foo, string>give"a" | "b"KeysOf<Foo, number>give "c"

我试过了type KeysOf<T, V> = T[infer K] extends V ? K : never,但是 TypeScript 不允许inferextends.

标签: typescript

解决方案


您可以使用映射类型和条件类型来执行此操作:

interface Foo {
   a: string
   b: string
   c: number
}


type KeyOf<T, V> = {
    [P in keyof T]: T[P] extends V ? P : never
}[keyof T]

type S = KeyOf<Foo, string> //"a" | "b"
type N = KeyOf<Foo, number> //"c"

推荐阅读