AnyCompiler

Generics

A generic function works with a type that's decided when the function is called, not when it's defined. It's how TypeScript expresses "this works the same way regardless of type" — an array-reversing function shouldn't need a separate version for strings and numbers.

function firstElement<T>(items: T[]): T {
  return items[0];
}

console.log(firstElement([1, 2, 3]));
console.log(firstElement(["a", "b", "c"]));
Output
1
a

T is a placeholder — TypeScript fills it in with whatever type you actually pass, and the return type is locked to match. firstElement([1, 2, 3]) is known to return a number; firstElement(["a", "b"]) is known to return a string.

Generic interfaces

Interfaces can be generic too — useful for a shape like "a box holding some value", where the value's type varies.

interface Box<T> {
  value: T;
}

let numberBox: Box<number> = { value: 42 };
let stringBox: Box<string> = { value: "hello" };

console.log(numberBox.value, stringBox.value);
Output
42 hello

Next: conditional statements — branching on a value, same as any other language.

Practice exercise

Write a generic function lastElement<T>(items: T[]): T that returns the last item in the array, then print lastElement([10, 20, 30]).