Búsqueda de sitios web

¿Existe un método para excluir directamente tipos de un tipo unión en Typescript?


Por ejemplo, quiero excluir los tipos de función de un tipo de unión dado.

type T = number | string | VoidFunction;  // a GIVEN type

type R = ExcludeType<T, VoidFunction>;  // number | string

Descubrí que puedo lograrlo agregando una función de herramienta como:

type T = number | string | VoidFunction;  // a GIVEN type

function f(v: T) {
  if (v instanceof Function) return undefined;
  return v;
}

type R = typeof f;  // number | string

Pero creo que es complejo e inexpandible, y tampoco puedo usarlo en archivos '.d.ts'.

¿Hay un enfoque mejor?

Respuesta #1

Es solo Exclude:

type R = Exclude<T, VoidFunction>;  // number | string

Patio de recreo


Exclude<Type, ExcludedUnion>

Construye un tipo excluyendo de Type todos los miembros de la unión que sean asignables a ExcludedUnion.

Artículos relacionados