Skip to content

Instantly share code, notes, and snippets.

@se7en00
Created September 9, 2019 02:44
Show Gist options
  • Select an option

  • Save se7en00/73293d525b3058540c334e3de800f4c8 to your computer and use it in GitHub Desktop.

Select an option

Save se7en00/73293d525b3058540c334e3de800f4c8 to your computer and use it in GitHub Desktop.
TS 实战演练

我在项目中遇到这样一种场景,需要获取一个类型中所有value为指定类型的key。 例如,已知某个React组件的props类型

interface SomeProps {
    a: string
    b: number
    c: (e: MouseEvent) => void
    d: (e: TouchEvent) => void
}

我需要“知道”(编程意义上)哪些参数是function类型。

思路: 我们需要从一个map得到一个set,而这个set是map的key的子集,筛选子集的条件是value的类型。 要构造set的子集,需要用到never;要实现条件判断,需要用到extends;而要实现key到value的访问,则需要索引取值。经过一些尝试后,解决方案如下:

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

type FunctionPropNames =  GetKeyByValueType<SomeProps, Function>;    // 'c' | 'd'

这里的运算过程如下:

// 开始
{
    a: string
    b: number
    c: (e: MouseEvent) => void
    d: (e: TouchEvent) => void
}
// 第一步,条件映射
{
    a: never
    b: never
    c: 'c'
    d: 'd'
}
// 第二步,索引取值
never | never | 'c' | 'd'
// never的性质
'c' | 'd'

链接:https://juejin.im/post/5d4285ddf265da03dd3d514b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment