user1
user1

Reputation: 586

Function parameters and type in Typescript

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 {}

Upvotes: 0

Views: 60

Answers (1)

Evaldas Buinauskas
Evaldas Buinauskas

Reputation: 14097

& 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;
}

Upvotes: 1

Related Questions