Sikau

TypeScript · Day 14 · about 25 min

Generic functions

One function, any type — still checked.

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.

The rest of this lesson

  • Generics keep informationexplain
  • Several type parametersexplain
  • What's the type of x?predict
  • Inferred Tpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript