I am currently working on a TypeScript function that takes an object as a parameter and deduces its type, then merges that inferred type with another type provided via generics. The outcome should be an object that includes properties from both the inferred type and the generic type.
My objective is as follows:
function addType<E extends object>(obj: any): // inferred object type + E {
// Implementation
}
const x = addType<{ extraProp: number }>({ someProp: 1 });
// The type of x should be:
// {
// someProp: number;
// extraProp: number;
}
The idea is for TypeScript to deduce the type of the obj
parameter (in this case, { someProp: number }
) and then combine it with the generic type { extraProp: number }
, resulting in the following type:
{
someProp: number;
extraProp: number;
}
Nevertheless, I aim to accomplish this by providing only one type argument ({ extraProp: number }
), rather than two. I want the function to deduce the type of the obj
parameter automatically.
I have attempted to utilize intersection types, conditional types, and various other methods, but I encounter challenges where TypeScript either expects two type arguments or fails to correctly deduce the type.
Does anyone know of a way to achieve this in TypeScript without explicitly specifying the inferred type?