×

typescript · level 2 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A function works for any type, and remembers which.

Picture a function that gives back the first item of an array. Write it for string[] and it is no use for numbers. Write a copy for each type and you repeat yourself. A generic function solves this with a .

A type parameter is a placeholder for a type, written in angle brackets after the name: function first<T>(items: T[]): T. Read T as “some type”. Each call fills it in: pass a number[] and T becomes number, so you get a number back.

You rarely need to say which type. The checker works it out from the arguments.

function first<T>(items: T[]): T {
  return items[0];
}
const top = first([42, 17, 8]);
const winner = first(["Ava", "Ben"]);
console.log(top + 1);
console.log(winner.toUpperCase());

T is a habit, short for type. Any name works, like Item.