TypeScript Generics

A generic function takes a type parameter, written <T>, so it can work with many types while still being checked. first<T> returns the first element of a T[] and has the return type T | undefined.

TypeScript
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const n = first([10, 20, 30]);
const s = first(["a", "b"]);
const none = first<number>([]);
console.log(n, s, none);
Read the full lesson