Prompteo

Unidad 7 · 1 min

Genéricos y tipos utilitarios

Escribir tipos reutilizables con parámetros, restringirlos y aprovechar los utilitarios de la librería estándar.

Genéricos y tipos utilitarios

Un genérico es un tipo con un parámetro. La función identidad es el ejemplo canónico:

function identity<Type>(arg: Type): Type {
  return arg;
}

Se puede indicar el tipo a mano o dejar que se infiera:

let output = identity<string>("myString");
let output = identity("myString");

También hay interfaces y clases genéricas:

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

class GenericNumber<NumType> {
  zeroValue: NumType;
  add: (x: NumType, y: NumType) => NumType;
}

Restricciones

extends limita qué tipos se aceptan:

interface Lengthwise { length: number }

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

Con keyof la clave queda atada al objeto:

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

Sobre { a: 1, b: 2, c: 3, d: 4 }, getProperty(x, "m") falla: '"m"' is not assignable to '"a" | "b" | "c" | "d"'.

Utilitarios

Partial, Required, Readonly, Record, Pick, Omit, Exclude, Extract, NonNullable, Parameters, ReturnType y Awaited ya vienen incluidos: son genéricos que transforman otros tipos sin repetir código.