Generics in Typescript
type Input = number | string
function firstElement(arr: Input[]): Input{
return arr[0];
}
const value = firstElement(["harsh", "chandwani", 9, 8, 7]);
console.log(value);
//console.log(value.toUpperCase());
//now let us take the generics into the call
//Defination: create components that work with any data type while still providing compile time type safety
//here is the code
//<T> -- generic thing, can be a number, can be a string, can be any
function identity<T>(arg: T[]): T {
return arg[1];
}
//we can also do
interface User {
name: string;
}
//if this wasnt the case, you have to make 2 functio ns that will handle this case, one for string, one for numbers (int)
let output1 = identity<string>(["MyString"]);
let output2 = identity<number>([1]);
let output3 = identity([{name: "harsh"}]);
This basically enables you to write one function, when you have different data types coming and the thing is the same, which basically helps to reduce the number of lines in the code, this is important, a larger function happens to be working for a number and strings, but internally the function is working same.
Thank you
Harsh Chandwani
Software Developer