Thuta Learning
AdvancedProgrammingintermediate

Generics

Relax. We'll talk through this in plain words — no textbook voice.

Generics let you build reusable components (functions, classes) that work across many types instead of being locked to just one. You use <T> (a type variable) to do this.

typescript
function getFirstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

let firstNumber = getFirstElement([1, 2, 3]);
let firstString = getFirstElement(["a", "b", "c"]);

console.log(firstNumber);
console.log(firstString);
You should see
1 a