Don't lose the type
A function returning the first item of an array works for numbers, strings, users… Typing it as unknown[] loses the type; writing one per type is silly. generics let a function take a type as a parameter, so the type flows through.
Type parameters
function first<T>(list: T[]): T | undefined {
return list[0];
}
const n = first([10, 20]);
const s = first(["a", "b"]);
console.log(n?.toFixed(1), s?.toUpperCase());
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
const p = pair("momo", 180);You rarely write the type argument yourself (first<number>(…)) — TypeScript infers it from the arguments.