Exclude object keys by their value type in TypeScript

会有一股神秘感。 提交于 2021-02-08 14:16:01

问题


I want to map an object type to a subtype that includes only keys whose values are of a specific type.

For example, something like ExtractNumeric<T>, where ExtractNumeric<{ str: string, num: number }> should be equivalent to the type: { num: number }

I've tried this, but it does not work:

type ExtractNumeric<T> = { [k in keyof T]: T[k] extends number ? T[k] : never }

This snippet throws a type error: let obj: ExtractNumeric<{ str: string, num: number }> = { num: 1 }

Because although the str key expects a value of never, the compiler complains about its absence.


回答1:


Linked aticle in the comment, but in a nutshell:

type SubType<Base, Condition> = Pick<Base, {
    [Key in keyof Base]: Base[Key] extends Condition ? Key : never
}[keyof Base]>;

type ExtractNumeric<T> = SubType<T, number>



来源:https://stackoverflow.com/questions/56431150/exclude-object-keys-by-their-value-type-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!