I'm struggling to understand the practical use of generics in typescript.
interface ICustomer
{
name: string;
age: number;
}
function CalculateAverageAge<c extends ICustomer>(customer1: c, customer2: c): number
{
return (customer1.age + customer2.age)/2;
}
resultingNumber = CalculateAverageAge({name: "Peter", age: 62},
{name: "Jason", age: 33});
In the given example, we pass interface 'c' to the function CalculateAverageAge.
However, without using 'extends ICustomer', we cannot access 'age' and 'name' inside that class.
So what is the purpose of passing 'template(c)' in the function? We could just write the code in the following format:
function CalculateAverageAge(customer1: ICustomer, customer2: ICustomer): number
{
return (customer1.age + customer2.age)/2;
}
Can you provide a real-world example where generics are truly beneficial?
Let me explain a scenario where I find using generics necessary.
interface t1{
a:String
b:number
}
interface t2 {
a:String
b:number
c:number
}
interface t3 {
a:String
b:number
d:number
}
class base<T extends t1> {
constructor( input : T, type:string ){
//some common code for both derived1 and derived2
if(type==="derived1"){
console.log(input.c);// will throw error because t1 doesn't contain c
} else if ( type==="derived2"){
console.log(input.d);// will throw error because t1 doesn't contain d
}
}
}
class derived1 extends<t2>{
constructor(){
var temp = {a:"11",b:2,c:3}
super(temp,"derived1");
}
class derived2 extends<t3>{
constructor(){
var temp = {a:"11",b:2,d:3}
super(temp,"derived2");
}
}
Is it possible to achieve this with generic?
If not, what would be the most efficient way to implement it while avoiding redundant code?