0

In the declaration of this function, if I remove <IFirst extends {}, ISecond extends {}>, the compiler reports an error; is not the return value the type after the double dot? What's the meaning of <IFirst extends {}, ISecond extends {}> after the name of the function? Why I have to put both <IFirst extends {}, ISecond extends {}> and : IFirst & ISecond on the declaration? I checked the documentation and surfed the Internet, but I cannot find the answer.

function extend<IFirst extends {}, ISecond extends {}>(
    IFirst: IFirst,
    ISecond: ISecond
): IFirst & ISecond {}
2
  • if I remove ,. What do you remove? Commented Aug 19, 2019 at 13:59
  • @Evaldas Buinauskas: sorry; question updated; format problems. Commented Aug 19, 2019 at 14:31

1 Answer 1

1

& is a intersection type and it's one of the advanced types in TypeScript.

It's going to combine all properties from IFirst and ISecond into one.

<IFirst extends {}, ISecond extends {}> is a generic type and extends keyword means that IFirst or ISecond has to be compatible with {}.

So basically this function accepts two parameters that can be cast to {} and will ensure that return type will have properties from both first and second objects.

function extend<TFirst extends {}, TSecond extends {}>(
    first: TFirst,
    second: TSecond
): TFirst & TSecond {
  return Object.assign({}, first, second);
}

const extended = extend({a: 1, b: 2 }, { c: 3, d: 4 });

console.log(extended);

extended will have a definition of:

const extended: {
    a: number;
    b: number;
} & {
    c: number;
    d: number;
}
Sign up to request clarification or add additional context in comments.

3 Comments

so <TFirst extends {}, TSecond extends {}> refers to the input parameters and not the output parameters, right?
In your case it dictates both, because it dictates the input and the output (intersection type). But normally you can think of them as dictating input parameters.
@Yellow75 You should read TypeScript documentation for more information about generics ;) And more specifically

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.