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 ??

>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

Leave a Reply