Skip to content

Instantly share code, notes, and snippets.

@khalidx
Created March 2, 2022 05:52
Show Gist options
  • Save khalidx/6a4f949346df30a655b02207383b566a to your computer and use it in GitHub Desktop.
Save khalidx/6a4f949346df30a655b02207383b566a to your computer and use it in GitHub Desktop.
Exclude a type from a TypeScript tuple or array.

The following block excludes the type undefined from a TypeScript tuple or array.

You can also replace undefined with something else to exclude another type, but YMMV, depending on the type and how you use it.

export type FilterUndefined<T extends unknown[]> = T extends [] ? [] :
  T extends [infer H, ...infer R] ?
  H extends undefined ? FilterUndefined<R> : [H, ...FilterUndefined<R>] : T

Usage:

type SomeTuple = [string, undefined, number]
type FilteredTuple = FilterUndefined<SomeTuple>  // type becomes [string, number]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment