Generics bring flexibility to our TypeScript code. You and I can write functions that work with any data type, eliminating the need to duplicate code for different scenarios. Think of generics as reusable templates that adapt to whatever data we throw at them.
Generic functions, interfaces, and classes help you and me create more maintainable code by abstracting away specific types. The syntax `
When you and I use generics, we get the benefits of type safety without sacrificing flexibility. The compiler helps catch type-related bugs early, while we keep our code DRY (Don't Repeat Yourself) and easy to understand.
Generic Functions
You and I can create functions that work with arrays of any type. These type-safe utilities become powerful tools in your TypeScript toolkit, helping you handle collections of data without losing type information.
function first(array: T[]): T {
return array[0];
}
function last(array: T[]): T {
return array[array.length - 1];
}
const numbers = [1, 2, 3, 4, 5];
const strings = ["a", "b", "c"];
console.log(first(numbers));
console.log(last(strings));
Try it Yourself โ