DEV Community

PuruVJ
PuruVJ

Posted on • Edited 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?

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay