07 generics

Generics keep type information moving through a function Using any throws that information away The identity function is the shortest example that shows why

Table of Contents

Identity

function identity<T>(value: T): T {
  return value;
}

T captures the caller’s type and returns it Call identity("x") and the result is string Call identity(1) and it is number

any would return any in both cases That is the difference

Constraints

interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

extends Lengthwise says the type must have length Calling logLength(3) fails because a number has no length Calling logLength([1, 2]) works

Generic types

function identity<T>(value: T): T {
  return value;
}

The generic function type can be named:

interface GenericIdentityFn {
  <T>(arg: T): T;
}

Putting <T> on the interface instead of the call signature locks the type when the interface is used That changes where the generic lives

keyof constraints

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

K extends keyof T stops you reading a property that does not exist getProperty({ a: 1 }, "a") works "m" fails with a type error

Defaults

type Box<T = string> = { value: T };

A default makes the type parameter optional Required parameters cannot follow optional ones

Posted