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

Generic type inference from parameter/object without function

I have a generic type:

type Alpha<T> = {
  enabled: boolean;
  params: T;
};

I want to create a variable like so:

const alpha: Alpha = {
  enabled: true,
  params: {
    title: "hello",
  },
};

But that won’t work because Alpha expects a type as argument. However, my whole point here is that I would like it to be infered directly.

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

Of course I could use a function like that:

const createA = <T>(params: T): Alpha<T> => {
  return {
    enabled: true,
    params,
  };
};

const beta = createA({ funny: "title" });

But I would like to avoid having to create a function to do that. Is that doable ?

>Solution :

TL;DR;
No, it’s not doable.

Currently, there is no ideal way other than a dummy generic function to infer the type correctly. The only valid option without a function would be to manually pass the generic parameter to the type:

const alpha: Alpha<{title: string}> = {
  enabled: true,
  params: {
    title: "hello",
  },
};
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