Array Includes Type

I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.

Let's create a type for the JavaScript Array.includes function in the type system. A type takes the two arguments. The output should be a boolean true or false.

The JavaScript Array.includes function looks like this:

const arr = ["a","b","c"]:
arr.includes("a") // true

And our type should should look something like this:

<Includes<[1, 2, 3, 5, 6, 7], 7> // true
<Includes<[1, 2, 3, 5, 6, 7], 4> // false

So what do we know?

  • We know that our type should take an array and a value as inputs.
  • We should take check if the desired value exist in the array
  • After checking against every element in the array, we return a boolean accordingly.
type Includes<TArray extends readonly unknown[], Value> = 
TArray extends [infer FIRST,... infer REST] ? 
Equal<Value,FIRST> extends true ? true : Includes<REST,Value> : false

For this type we need to the Equal utility type which checks if two inputs are equal.

TArray extends readonly unknown[] We first check our TArray is of type array.

Understanding the infer keyword

The infer keyword can be used within a condition in a conditional type to put the inferred type into a variable. That inferred variable can then be used within the conditional branches.

TArray extends [infer FIRST,... infer REST] We infer the first element of the array and then rest of elements.

Equal extends true We check if that first element is equal to our desired value, if so, we got it and therefore we should return true. Otherwise we recursively check again with the rest of the elements : Includes<REST,Value>

Lastly, if the element is not to be found in the array we return false : false

This one was a tough one, but we learned how The includes function works under the hood.

Thank you!