1

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;
}
accelerate
  • 1,215
  • 3
  • 16
  • 30
  • Does this answer your question? [How to write PickByValue type?](https://stackoverflow.com/questions/55150760/how-to-write-pickbyvalue-type) – kaya3 Dec 10 '20 at 09:25
  • Nope, not really, unless I misunderstood the question & answer in your link. That seemed to be filtering by a specific value, but I wanted to filter by a specific type (unless the answer works for types as well?). The accepted answer below was what I was after. – accelerate Dec 10 '20 at 10:04
  • The question I linked is about types. The word "value" in this context is as opposed to "key", i.e. `Pick` picks by key type and `PickByValue` picks by value type. – kaya3 Dec 10 '20 at 13:58
  • 1
    The answer below is practically identical to the answer to the linked duplicate, by the way. – kaya3 Dec 10 '20 at 14:00

1 Answers1

1

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

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
  • 1
    Thanks. This was what I needed. I made it more generalized by changing the signature to `KeysByType = = { [P in keyof T]: T[P] extends K ? P : never }[keyof T]` – accelerate Dec 10 '20 at 10:02
  • In TypeScript 4.1, this can be a one-liner: `type StringEntries = { [P in keyof T as T[P] extends string ? P : never]: T[P] }`. – Nate Whittaker May 16 '23 at 19:05