Want a faster signal before interviews? Take the Interview Ready Check →

DAY 21 OF 30

Generics

Yesterday, in one sentence

What is an enum in TypeScript?

Interview question

What is the difference between an enum and a literal union, and which one uses structural typing?

You may have two functions that do exactly the same thing but just expect different types. A generic functionGeneric Function lets you write one function with the type as a parameter, decided when the function is called. This prevents you from writing the same function twice.

type Hero = { good: boolean };
type Villain = { evil: boolean };

function getFirstHero(heroes: Hero[]): Hero {
  return heroes[0];
}

function getFirstVillain(villains: Villain[]): Villain {
  return villains[0];
}

The body of getFirstHero is identical to the body of getFirstVillain. Only the types differ.

A generic function declares a type parameter in angle brackets after the function name.

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

T is the type parameter. It is used for the function parameter as T[] and again as the return typeReturn Type, so all three refer to the same type. When the function is called, TypeScript infers what T is from the argument.

getFirst(heroes);
// TypeScript reads it as: getFirst<Hero>(items: Hero[]): Hero

getFirst(villains);
// TypeScript reads it as: getFirst<Villain>(items: Villain[]): Villain

A type aliasType Alias can declare a type parameter too, making it a generic typeGeneric Type.

type Pair<T> = {
  first: T;
  second: T;
};

let ranks: Pair<number> = { first: 1, second: 2 };

There is no argument here for TypeScript to infer from, so you pass the type in the angle brackets yourself when you use the alias.

Check yourself

What is the return type of wrap("Logan")?
function wrap<T>(value: T): T[] {
  return [value]
}
What are generics in TypeScript, and why are they useful?