I am trying to create a function in TypeScript that takes an object as an argument and infers its type, then combines that inferred type with another type provided via generics. The result should be an object that has the properties of both the inferred type and the generic type.
Here is what I want to achieve:
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 goal is to have TypeScript infer the type of the obj
parameter (in this case, { someProp: number }
) and then merge it with the generic type { extraProp: number }
, so that the resulting type is:
{
someProp: number;
extraProp: number;
}
However, I want to achieve this by only providing one type argument ({ extraProp: number }
), not two. I want the function to infer the type of the obj
parameter automatically.
I’ve tried using intersection types, conditional types, and other approaches, but I keep running into issues where TypeScript either expects two type arguments or does not infer the type correctly.
Is there a way to achieve this in TypeScript without manually specifying the inferred type?
1