typescript generics series - arrays

base technics - array#

This collection of basic technics really helped me to get an better understanding how we can work with array types in generics. It is quite amazing what we can do if we get used to the sometimes strange syntax of types in typescript.

Spoiler alert! This section contains some solutions of the great type-challenge.

enumerate the array keys#

get all keys

This technic is helpfull if we want to convert a static runtime array into an type. You can mark the array as const and extract the resulting type which contains all keys of the array. Pretty cool.

const fruits = ['apple', 'bannana', 'cherry'] as const
type Fruit = typeof fruits[number]

get keys of array

type Keys<T extends any[]> = T[number];

array functions#

To understand the following methods we need to know how the infer Keyword works. If you want a small refresher you can visit “the infer keyword”.

includes#

type Includes<T extends any[], V> = 
  V extends T[number] ? true : false

concat#

type Concat<T extends any[], U extends any[]> = [...T, ...U]

push#

type Push<T extends any[], U> = [...T, U] 

unshift#

type Unshift<T extends any[], U> = [U, ...T] 

first#

type Last<T extends any[]> = 
  T extends [infer First, ...any[]] ? First : never;

last#

type Last<T extends any[]> = 
  T extends [...any[], infer TLast] ? TLast : never;

every - check every element in an array#

This is one of the really important basics. It shows how you can check every item in an array trough recursion.

type Every<T extends any[]> =  
  T extends [infer F, ...infer R]
    ? Check<U, F> extends true ? Every<R, U> : false
  : true;

summary#

It is quite impressive what we can do with the typing system in typescript. Arrays are one part to let you successfully work with generics.