advanced#TypeScript#Generics#Reusability
TypeScript Generics Tutorial
Learn about TypeScript generics and how to use them to create reusable functions.
Introduction to Generics
In TypeScript, generics are a way to create reusable functions that can work with multiple types.
Step 1: Define a Generic Function
Create a new file called utils.ts and add the following code:
function first<T>(arr: T[]): T {
return arr[0];
}
This function returns the first element of an array of any type.
Step 2: Use the Generic Function
Add the following code to the utils.ts file:
console.log(first([1, 2, 3]));
console.log(first(['a', 'b', 'c']));
This code uses the first function with arrays of different types.
Step 3: Create a Generic Class
Add the following code to the utils.ts file:
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
This class is a generic container that can hold any type of value.