最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Exclude object keys by their value type in TypeScript - Stack Overflow

programmeradmin3浏览0评论

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 piler plains about its absence.

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 piler plains about its absence.

Share Improve this question asked Jun 3, 2019 at 16:20 prmphprmph 8,21612 gold badges40 silver badges47 bronze badges 2
  • medium./dailyjs/… seems that's exactly answers your question – vittore Commented Jun 3, 2019 at 16:32
  • 2 type ExtractNumeric<T> = Pick<T, { [k in keyof T]-?: T[k] extends number ? k : never }[keyof T]> let obj: ExtractNumeric<{ str: string, num: number }> = { num: 1 } Although for sure a duplicate .. – Titian Cernicova-Dragomir Commented Jun 3, 2019 at 16:32
Add a ment  | 

1 Answer 1

Reset to default 18

Linked aticle in the ment, 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>

发布评论

评论列表(0)

  1. 暂无评论