accelerate
accelerate

Reputation: 1353

Using Pick to retrieve all keys of a certain type

Is there a way to use Pick<T, K> to extract all keys of a certain type?

Example:

type MyObject = {
  a: string;
  b: number;
  c: string;
  d: boolean;
}

I want to extract all string types, so final type will be:

type NewType = {
  a: string;
  c: string;
}

Upvotes: 3

Views: 2109

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37948

First you'll need to extract all keys which have string value types:

type StringKeys<T> = { [P in keyof T]: T[P] extends string ? P : never }[keyof T]

type NewType = Pick<MyObject, StringKeys<MyObject>>; // { a: string; c: string; }

Playground

Upvotes: 4

Related Questions