0

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I feel kind of dumb. I had looked at the 'mixins' and 'declaration merging' part of the documentation. Thanks for pointing me in the right direction. I'm sure this question and your answer will still be useful for other TypeScript newbies like me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.