Before I start I want you to know that I am Latino and I am not very good at English so I had to use google to translate my question. I hope you can help me.
I am learning typescript and I have just entered the topic of generics, everything was fine but I found an example that I cannot understand. In the following image, how is it that typescript knows that the generic parameters of the "compare" function are <number, string>?
class Pair<K, V> {
constructor(public key: K, public value: V) {}
}
function compare <K,V> (pair1: Pair<K,V>, pair2: Pair<K,V>): void {
console.log(pair1, pair2);
}
let p1 = new Pair(1, "Apple");
let p2 = new Pair(1, "Orange");
compare(p1, p2);
Supposedly these types are inferred from the arguments that are sent therefore calling the function should look like this.
compare<Pair<number, string>, Pair<number, string>>();
I can't understand it. Another thing that I noticed is that it seems that it takes the types of the first argument because if the second object has different types it will show me an error like in this image
class Pair<K, V> {
constructor(public key: K, public value: V) {}
}
function compare <K,V> (pair1: Pair<K,V>, pair2: Pair<K,V>): void {
console.log(pair1, pair2);
}
let p1 = new Pair(1, "Apple");
let p2 = new Pair('dani', "Orange");
compare(p1, p2); //error in second argument
I hope you can help me. I wish you all an excellent day.