Assuming that lodashMerge
refers to lodash's _.merge
method, you will encounter limitations if you solely rely on this method. To address this issue while maintaining the functionality of the method, it is necessary to encapsulate it within a custom function where a more specific type definition can be implemented. The current definition provided by lodash is overly lenient for your requirements.
The detailed type definition for this method can be accessed here. Upon examination, it reveals that each overload's return type is an intersection of its arguments, whereas you seek the exact type of the initial argument as the return type.
To resolve this, I recommend creating a wrapper function with a desired signature. Here is a potential implementation:
// Utilizing only the final overload (variadic) for future reference.
declare function lodashMerge(object: any, ...otherArgs: any[]): any;
type DeepPartial<T> = {
[K in keyof T]?: DeepPartial<T[K]>;
}
function myMerge<T>(base: T, ...args: DeepPartial<T>[]): T {
return lodashMerge(base, ...args);
};
By employing this approach, errors will be flagged in your second example but not the first. (Note: In both examples, an error occurs due to the misspelling of "dimensions".)
// No issues, functions correctly.
const child : Human = myMerge(base,{
age:22,
dimensions:{ // Corrected spelling; without correction, error would occur.
height:99
}
})
// Error: Refer to explanation below
const child2 : Human = myMerge(base,{
hairColor:'red' // Error: Object literal may only specify known properties, and 'hairColor' does not exist in type 'DeepPartial<Human>'.
})