Introduction
Generics let us write flexible code that works with many types without repeating ourselves. They help keep code safe and clear.
Generics let us write flexible code that works with many types without repeating ourselves. They help keep code safe and clear.
function identity<T>(arg: T): T { return arg; }
T is a placeholder for any type you provide later.
You use <T> after the function name to declare a generic type.
function identity<T>(arg: T): T { return arg; }
string as the type.const output = identity<string>("hello");
function loggingIdentity<T>(arg: T[]): T[] { console.log(arg.length); return arg; }
This program shows how the generic function identity returns the same value and type you give it.
function identity<T>(arg: T): T { return arg; } const num = identity<number>(42); const str = identity<string>("hello"); console.log(num); console.log(str);
Generics help avoid using any, which loses type safety.
You can use multiple generic types like <T, U> if needed.
Generics make code reusable and type-safe.
They let you write one function or component for many types.
Using generics helps catch errors early and keeps code clear.
function identity<T>(arg: T): T { return arg; }identity uses <T> to accept any type and return the same type.<T> and uses arg: T with return type T.arg. function example<T>(arg: T) { return arg; } misses return type.function wrapInArray<T>(value: T): T[] { return [value]; }
const result = wrapInArray(5);
console.log(result);wrapInArray(5) returns an array with one element: 5.function getFirstElement<T>(arr: T) {
return arr[0];
}arr is typed as T, but it should be an array of T to use arr[0].arr: T to arr: T[] so the function accepts an array.T[] and return an object mapping strings to numbers.arr: T which is incorrect for arrays. function mapToIndex(arr: any[]): any {
const result = {};
arr.forEach((item, index) => { result[item] = index; });
return result;
} uses any losing type safety. function mapToIndex<T>(arr: T[]): T[] {
return arr.map((item, index) => index);
} returns an array of indexes, not the mapping object.Pass the test and this pattern moves unknown