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 generic get typeof dynamic nested key

I have a generic type, and I want to get typings for the nested key to be typed correctly. Is it achievable, right now it does not work

export type Config = {
  [K: string]: {
    [M: string]: {
      options: string[];
      type?: 'checkbox' | 'toggle';
    };
  };
};

export interface FiltersProps<T extends Config, M extends keyof T, X extends keyof M> {
  config: T;
  values: {
    [K in M]: string[];
  };
}

Example:

const config = {
  statuses: {
    done: {},
    expired: {},
  },
};

const filterProps = {
  config,
  values: {
    done: [], <-- correctly typed
    expired: [], <-- correctly typed
  },
};

how do i get correct typings for keys in values ??

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

>Solution :

You have to update the mapped type a bit. You typed X incorrectly, it should be keyof T[M] not, keyof M, since M will be some key, which is typed as number | string | symbol.

interface FiltersProps<T extends Config, M extends keyof T = keyof T> {
  config: T;
  values: {
    [K in keyof T[M]]: string[];
  };
}

Testing:

const filterProps: FiltersProps<typeof config> = {
  config,
  values: {
    done: [],
    expired: [],
  },
};

playground

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