Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript deep Pick by key without specifying a path

Let’s say I’ve this type

type Form = {
  collateral: {
      id: "collateralField",
      default: "",
      deps: ["collateralToken", "borrowInput", "asd"],
      severities: {
          first: 'first',
          second: 'second'
      }
  },
  borrow: {
    id: "borrowField",
    name: "Borrow"
  },
}

I’d like to create a generic that takes the type Form and a string Query. It should return an union of all the values of the Queried keys.

type IDs = DeepKeys<Form, "id">
// Expected: "collateralField" | "borrowField"

This is my progress

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type DeepKeys<T, Q> =
  T extends object 
    ? { [K in keyof T]: (K extends Q ? T[K] : never) | DeepKeys<T[K], Q> }[keyof T]
    : never;

Typescript Playground

It seems to loop into the array object and append some unnecessary stuff.

>Solution :

You nearly got it.

The problem is that TypeScript is recurisively iterating over all keys, including those of arrays. That creates issues as there are unncecessary keys in your final type.

Here is a fix:

type DeepKeys<T, Q> = T extends object 
  ? {
    [K in keyof T]: T[K] extends (infer R)[]
      ? never
      : K extends Q 
        ? T[K]
        : DeepKeys<T[K], Q>
    }[keyof T]
  : never;

Just tested this out and seemed to work fine on the TS playground.

With this improved version, you can do the following

type IDs = DeepKeys<Form, "id">;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading