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.
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:
type isPillarMen = Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Dio'> // expected to be `false`Change the following code to make the test cases pass (no type check errors).
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>
: falseKey concepts:
Equal type for exact type comparisonEqual ensures exact matches (e.g., 1 | 2 doesn't match 1)readonly modifiers and union types correctlyThis pattern is essential for building robust type-level algorithms that require precise type matching.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount