//Simple Generic
function echo(data:any){
return data;
}
console.log(echo("Max").length); //Can put method also
//However, IDE did not show length method which means it did not know that the function returned is a string
//Bottom if put length will show undefined instead of compilation error
console.log(echo(27));
console.log(echo({name:"Max", age: 27}));
//Objective: let TS know that although accept generic data, but can know the type returned from it
//Better Generic
function betterEcho<T>(data: T){ //Makes it a generic function, can be any character
return data;
}
//Telling TS when using this function, give us the type so that we can use the type in the parameters
console.log(betterEcho("Max").length); //Will show the method
console.log(betterEcho<number>(27)); //Will not have this method and will show the error
console.log(betterEcho({name:"Max", age: 27}));
//Built-in Generics
//1. Arrays
const testResults: Array<number> = [1.94, 2.33];
testResults.push(1); //works
testResults.push("string") //wrong
//2. Assign Generic Type to be an Array
function printAll<T>(args: T[]){
args.forEach( el => console.log(el));
}
printAll<string>(["Apple", "Banana"])
//Generic Types
const echo2: <T>(data:T) => T = echo;
console.log(echo2<string>("Something"));
//Generic Class
//Problem
class SimpleMath {
baseValue;
multiplyValue;
calculate(){
return this.baseValue * this.multiplyValue;
}
}
const simpleMath = new SimpleMath();
simpleMath.baseValue = 10; //if change to "something", no compilation error
simpleMath.multiplyValue = 20;
console.log(simpleMath.calculate());
//Solution - change to generic class
class SimpleMath<T> {
baseValue: T;
multiplyValue: T;
calculate(): number{
return +this.baseValue * +this.multiplyValue; //explicitly cast the value "+"
}
}
const simpleMath = new SimpleMath();
simpleMath.baseValue = 10; //if changed to "something", no compilation error
simpleMath.multiplyValue = 20;
console.log(simpleMath.calculate());
//Solution 2
class SimpleMath<T extends number | string> { //set a costraint and then add option of string and if given "10", will cast to Number
baseValue: T;
multiplyValue: T;
calculate(): number{
return +this.baseValue * +this.multiplyValue; //explicitly cast the value "+"
}
}
const simpleMath = new SimpleMath<number>();
class SimpleMath<T extends number | string, U extends number | string> {
baseValue: T;
multiplyValue: U;
calculate(): number{
return +this.baseValue * +this.multiplyValue;
}
}
const simpleMath = new SimpleMath<string, number>();
simpleMath.baseValue = "10";
simpleMath.multiplyValue = 20;
console.log(simpleMath.calculate());