FRONTENDO
Emberhold Forge
0
0
TypeScript · Generics
New technique

One mould, many metals

Why forge a separate mould for iron, bronze and gold? Make one that fits them all.

Say you want first: it returns the first item of any array. You could write it once for number[], again for string[], again for every type. Or you could type it with any, but then the result is any too and all checking is gone.

A generic solves this. It adds a type parameter <T>: a placeholder that gets filled in with the real type at each call. Pass a number[] and T is number; pass a string[] and T is string.

function firstAny(items: any[]): any {
  return items[0];      // result: any - no checks
}

function first<T>(items: T[]): T {
  return items[0];      // result: the array's own type
}
  • T links input and output: an array of T goes in, a T comes out.
  • You declare <T> once, after the function name, then use it like any other type.