Typescript: Remove entries from tuple type

not sure if this is possible, but I would like to be able to define a type that converts tuples like: [number, string, undefined, number] to [number, string, number] (ie filter out undefined).

I thought about something like this:

type FilterUndefined<T extends any[]> = {
    [i in keyof T]: T[i] extends undefined ? /* nothing? */ : T[i];

Sadly I am am pretty sure that there is no way to achieve this.


Got it! But it need a lot of recursive magic:

type PrependTuple<A, T extends Array<any>> =
  A extends undefined ? T : 
  (((a: A, ...b: T) => void) extends (...a: infer I) => void ? I : [])

type RemoveFirstFromTuple<T extends any[]> = 
  T['length'] extends 0 ? undefined :
  (((...b: T) => void) extends (a, ...b: infer I) => void ? I : [])

type FirstFromTuple<T extends any[]> =
  T['length'] extends 0 ? undefined : T[0]

type NumberToTuple<N extends number, L extends Array<any> = []> = {
  true: L;
  false: NumberToTuple<N, PrependTuple<1, L>>;
}[L['length'] extends N ? "true" : "false"];

type Decrease<I extends number> = RemoveFirstFromTuple<NumberToTuple<I>>['length']
type H = Decrease<4>

type Iter<N extends number, Items extends any[], L extends Array<any> = []> = {
  true: L;
  false: Iter<FirstFromTuple<Items> extends undefined ? Decrease<N> : N, RemoveFirstFromTuple<Items>, PrependTuple<FirstFromTuple<Items>, L>>;
}[L["length"] extends N ? "true" : "false"];

type FilterUndefined<T extends any[]> = Iter<T['length'], T>
type I = [number, string, undefined, number];
type R = FilterUndefined<I>


How it works:

PrependToTuple is util that takes item A and list T and add it on first place when A is not undefined. PrependToTuple<undefined, []> => [], PrependToTuple<undefined, [number]> => [number]

RemoveFirstFromTuple works pretty mach i the same way

NumberToTuple is recursively check if length of final Tuple is N, if
not he add 1 to recursive call. This util is needed to create Decrease util.

And the most important z Iter works like recursive loop, when length of final tuple is N (size of Input) its return Output, but PrependToTuple is not increasing length when we try do add undefined, so when Iter<FirstFromTuple<Items> extends undefined we have to decrease N.

Source : Link , Question Author : Jan van Brügge , Answer Author : Przemyslaw Jan Beigert

Leave a Comment