Generics
Sometimes, we may want to repeat blocks of code for different data types. An example of same function with two different data types
function fun(props: string) {return args;}function fun(props: number) {return args;}
We use the same function with two different types. Generics can help us create a more generalized function for different data types For example -
function myFunc<T>(input: T): T {return input}const result = myFunc({ name: 'Shaan Alam' }) // T { name: string }const result2 = myFunc({ name: ['Shaan Alam'] }) // T { name: string[]
Creating Type-Safe Generics 👨💻
For creating type-sage generics, we're gonna use <T>
parameter around functions.
function fun<T>(args: T): T {return args;}const result = fun<string>("Shaan Alam"); // fun with string typeconst result1 = fun<number>(19); // fun with number typeconst result2 = fun<boolean>(true); // fun with boolean type
Using generics with many parameters
We can also use generics with many types.
function fun<T, U, V>(args1:T, args2: U, args3: V): V {return args3;}