#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).

ChallengeSolution
/* _____________ Your Code Here _____________ */

type Includes<T extends readonly any[], U> = any

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'

type cases = [
  Expect<
    Equal<Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Kars'>, true>
  >,
  Expect<
    Equal<Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Dio'>, false>
  >,
  Expect<Equal<Includes<[1, 2, 3, 5, 6, 7], 7>, true>>,
  Expect<Equal<Includes<[1, 2, 3, 5, 6, 7], 4>, false>>,
  Expect<Equal<Includes<[1, 2, 3], 2>, true>>,
  Expect<Equal<Includes<[1, 2, 3], 1>, true>>,
  Ex

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

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