Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude object keys by their value type in TypeScript

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.

like image 958
prmph Avatar asked Jun 03 '19 16:06

prmph


People also ask

How do I omit multiple keys in TypeScript?

To omit multiple keys from an object, pass a union of string literals in K . In the next example, we generate a Person type off of SoccerPlayer by removing the team and careerGoals .

How do you omit a property in TypeScript?

Use the Omit utility type to exclude a property from a type, e.g. type WithoutCountry = Omit<Person, 'country'> . The Omit utility type constructs a new type by removing the specified keys from the existing type. Copied!

How does exclude work in TypeScript?

In TypeScript, the Exclude utility type lets us exclude certain members from an already defined union type. That means we can take an existing type, and remove items from it for specific situations.

What does Keyof do in TypeScript?

keyof is a keyword in TypeScript which is used to extract the key type from an object type.


Video Answer


1 Answers

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>

like image 130
vittore Avatar answered Oct 06 '22 00:10

vittore