#898Easy

Includes

Check if an array includes a value at the type level. Learn about recursive types and type equality in this easy-level TypeScript challenge on TypeScriptPro.

Search arrays for exact type matches with Includes!

In this easy-level challenge, you'll implement the JavaScript Array.includes function in TypeScript's type system. This type checks whether a specific type exists within a tuple and returns a boolean literal type (true or false).

This challenge teaches important concepts about type equality, recursive type checking, and handling edge cases like readonly modifiers. You'll learn why TypeScript's extends isn't always sufficient for type comparison.

Challenge Instructions: Includes

Easy

Implement the JavaScript Array.includes function in the type system. A type takes the two arguments. The output should be a boolean true or false.

For example:

[object Object]

Change the following code to make the test cases pass (no type check errors).

Loading...

Video Walkthrough

Detailed Explanation

The Includes type requires careful handling of type equality, as extends alone isn't sufficient for exact matching.

type Equal<X, Y> =
  (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2
    ? true
    : false
 
type Includes<T extends readonly any[], U> = T extends [
  infer First,
  ...infer Rest,
]
  ? Equal<First, U> extends true
    ? true
    : Includes<Rest, U>
  : false

Key concepts:

This pattern is essential for building robust type-level algorithms that require precise type matching.

This challenge is originally from here.

Share this challenge

Become a TypeScript Pro

Track your progress through 100+ hands-on challenges. Free, sign in with GitHub.

Or start solving right away: explore all TypeScript challenges