theory.ts

Generics

Generic Functions

Generics allow functions to work with different data types while maintaining type safety.

  • Generics use a type parameter `<T>` to define flexible types.
  • TypeScript infers the type when the function is called.
  • Multiple type parameters allow handling different types.
// Function with a generic type parameter
function identity<T>(value: T): T {
  return value;
}

console.log(identity("Hello")); // "Hello"
console.log(identity(42)); // 42

// Function with multiple generic types
function pair<T, U>(first: T, second: U): [T, U] {
  return [first, second];
}

console.log(pair("Alice", 30)); // ["Alice", 30]