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.
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",
},
};