DEV Community

PuruVJ
PuruVJ

Posted on • Updated on

How to infer recursive types with generics

I have a helper function that infers types from the keys of object I pass to it. Helps in autocomplete.

I'm stuck at the point where I wanna add a menu property to my object, and that menu property is recursive, that is it references the original object it is part of:

Here's my current code:

export type IMenu = {
  title: string;
  breakAfter?: boolean;
  menu?: typeof createMenuConfig;
};

/**
 * This is just a helper function to infer types from the object passed to it
 */
export const createMenuConfig = <T>(et: { [K in keyof T]: IMenu }) => et;
Enter fullscreen mode Exit fullscreen mode

But this doesn't work.

Error is weird:

Type '{ hello: { title: string; }; }' is not assignable to type '<T>(et: { [K in keyof T]: IMenu; }) => { [K in keyof T]: IMenu; }'.
  Object literal may only specify known properties, and 'hello' does not exist in type '<T>(et: { [K in keyof T]: IMenu; }) => { [K in keyof T]: IMenu; }'.ts(2322)
Enter fullscreen mode Exit fullscreen mode

How I can I fix the problem?

Top comments (0)