Reputation: 6873
Given a function that takes in two objects of different types, object A and object B, merges both objects into one and returns that merged object:
/**
* @description Merge the contents of two objects into a single object
* @param {Object} target The target object of the merge
* @param {Object} ex The object that is merged with target
* @return {Object} The target object
* @example
* var A = {a: function() {console.log(this.a}};
* var B = {b: function() {console.log(this.b}};
*
* pc.extend(A,B);
* A.a();
* // logs "a"
* A.b();
* // logs "b"
*/
This is what i came up with but somehow I'm not sure this is right:
function extend<T>(target: T, ex: T): T
What should the function declaration look like? Should I be using generic types for this? How do I define the merged type being returned?
Upvotes: 0
Views: 83
Reputation: 134841
You're describing an Intersection Type, a combination of multiple types. Your scenario is even explained in the documentation.
In your case, you'll need to introduce a second generic parameter, to represent the other type. Your signature should look like this:
function extend<T, U>(target: T, ex: U): T & U
Upvotes: 3