Skip to content
jshacks.dev
TypeScript

Type Challenge: Implement Includes in TypeScript

Solve the Includes type challenge in TypeScript with a recursive conditional type and a strict Equal check, and see why a plain extends test is wrong.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Node.js and Vite logos.

The Includes challenge asks you to write a type that answers one question about a tuple: does it contain a given type? The JavaScript version is Array.prototype.includes, and the type-level version sounds just as simple. It is harder than it looks, because the obvious solution gets several edge cases wrong, and fixing it means understanding what "the same type" means to the compiler. This post states the challenge, gives a correct solution, walks through each part, tests it with type assertions, and shows the exact failure you get from the naive attempt. It describes TypeScript 6.x, and the same code compiles under the native compiler preview that TypeScript 7 is built on. The language features used are covered in the handbook chapters on conditional types and inference in conditional types.

The challenge

Start from this skeleton and make the tests pass.

includes.tsTypeScript
type Includes<T extends readonly unknown[], U> = any;

Includes<T, U> should be true if some element of the tuple T is exactly the type U, and false otherwise. The word "exactly" is the hard part. A tuple of [1 | 2] does not include 1, because its single element is the union 1 | 2, not 1. A tuple of [{ a: "A" }] does not include { readonly a: "A" }, because the two object types differ in a modifier. The solution has to tell these apart.

The solution

includes.tsTypeScript
type Equal<X, Y> =
  (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2)
    ? true
    : false;

type Includes<T extends readonly unknown[], U> =
  T extends readonly [infer First, ...infer Rest]
    ? Equal<First, U> extends true
      ? true
      : Includes<Rest, U>
    : false;

The type walks the tuple from the front. If the tuple has a first element, it compares that element with U using Equal. If they are identical, the answer is true. If not, it recurses on the rest of the tuple. When the tuple is empty, the pattern readonly [infer First, ...infer Rest] no longer matches, and the answer is false.

Walking through it

The condition T extends readonly [infer First, ...infer Rest] does two things at once. It tests whether T has at least one element, and it names the first element First and the remaining elements Rest. This is inference inside a conditional type. For T = [1, 2, 3], First is 1 and Rest is [2, 3]. For T = [], the pattern needs at least one element, so the check fails and the false branch runs.

The readonly in the pattern matters. A tuple produced by as const is a readonly tuple, and a readonly tuple does not extend the mutable pattern [infer First, ...infer Rest]. If you leave readonly out, then Includes<readonly [1, 2], 1> falls straight to the false branch, which is a silent wrong answer rather than an error. The constraint on T also uses readonly unknown[] for the same reason: a mutable tuple is assignable to it, and a readonly one is too.

Then comes the comparison. Equal<First, U> extends true runs the strict equality check, and on a match we return true immediately. Otherwise the type calls itself with Rest, which is the recursion. Each step removes one element, so the recursion ends when the tuple is empty. TypeScript allows deep recursion in tail position, and a conditional type whose recursive call is the whole result of a branch is a tail call that the compiler can optimise, so reasonably long tuples are fine.

Why a naive extends check is wrong

The natural first attempt is to ask whether U is one of the tuple's element types.

includes.tsTypeScript
type NaiveIncludes<T extends readonly unknown[], U> =
  U extends T[number] ? true : false;

type A = NaiveIncludes<[1, 2, 3], 2>;
type B = NaiveIncludes<[1], 1 | 2>;
type C = NaiveIncludes<[boolean], true>;

const b: B = "x";
const c: C = "x";
Text
includes.ts(8,7): error TS2322: Type 'string' is not assignable to type 'boolean'.
includes.ts(9,7): error TS2322: Type 'string' is not assignable to type 'true'.

The errors reveal the answers. B is boolean, not false. The type parameter U is a naked type parameter on the left of extends, so the conditional is distributive. The union 1 | 2 is split into 1 and 2, each is checked separately, and the results true and false combine into boolean. C is true, but the tuple holds boolean, which is a different type from true, so the challenge wants false. Both answers are wrong.

The lesson is that extends tests assignability, not identity. Assignability answers "can a value of this type be used where that type is expected", which is a looser question than "are these the same type". For membership you need identity, and that is what Equal provides.

How Equal works

The helper compares two function types.

equal.tsTypeScript
type Equal<X, Y> =
  (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2)
    ? true
    : false;

Each side is a generic function whose return type is a deferred conditional on X or Y. For one such function to be assignable to the other, the compiler requires the two conditional types to be identical, because it cannot resolve a conditional that depends on an unresolved T. The identity check it uses is strict: any is only identical to any, a readonly property differs from a mutable one, and 1 | 2 differs from 1. A plain two-way check such as X extends Y ? Y extends X ? true : false : false would treat some of these as equal, in particular anything involving any. This trick is not documented as a language feature, and it relies on how the compiler compares deferred conditional types, which is why it is the convention in type challenge repositories and not a guarantee. It has been stable across many releases.

Testing with type assertions

includes.test.tsTypeScript
type Expect<T extends true> = T;

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>>,
  Expect<Equal<Includes<[{}], { a: "A" }>, false>>,
  Expect<Equal<Includes<[boolean, 2, 3, 5, 6, 7], false>, false>>,
  Expect<Equal<Includes<[true, 2, 3, 5, 6, 7], boolean>, false>>,
  Expect<Equal<Includes<[false, 2, 3, 5, 6, 7], false>, true>>,
  Expect<Equal<Includes<[{ a: "A" }], { readonly a: "A" }>, false>>,
  Expect<Equal<Includes<[{ readonly a: "A" }], { a: "A" }>, false>>,
  Expect<Equal<Includes<[1], 1 | 2>, false>>,
  Expect<Equal<Includes<[1 | 2], 1>, false>>,
  Expect<Equal<Includes<[null], undefined>, false>>,
  Expect<Equal<Includes<[undefined], null>, false>>,
  Expect<Equal<Includes<readonly [1, 2], 2>, true>>,
];
Text
(no output: the file compiles without errors)

Each case is one of the edge cases above. If you swap the solution for the naive version, the case with [1] and 1 | 2 fails, because the naive type gives boolean where the test expects false, and the compiler reports the failure on the Expect line.

Text
includes.test.ts(14,10): error TS2344: Type 'false' does not satisfy the constraint 'true'.

If you remove readonly from the pattern inside Includes, the last case fails the same way, because the readonly tuple never matches.

Using Includes in real code

A type-level membership test is useful for constraining configuration. For example, a function can require that a list of allowed roles contain a role before a call is accepted.

roles.tsTypeScript
const roles = ["admin", "editor", "viewer"] as const;

type Allowed<R extends string> = Includes<typeof roles, R> extends true ? R : never;

function grant<R extends string>(role: Allowed<R>): void {
  console.log("granted " + role);
}

grant("editor");
grant("owner");
Text
roles.ts(10,7): error TS2345: Argument of type 'string' is not assignable to parameter of type 'never'.

The first call is accepted and prints granted editor at run time if you execute the program. The second call fails at compile time because the role is not in the list, so Allowed<"owner"> is never. The exact wording of the message can vary with the inference path, but the failure is real and appears before the code runs. This is a toy, and in application code a union of string literals made from the tuple, (typeof roles)[number], is usually simpler and gives better messages. The type-level Includes earns its place when the question is about the structure of a tuple rather than membership in a simple union.

Common mistakes

The first mistake is using extends for the comparison and treating it as equality, which fails on unions, boolean and any. The second is forgetting readonly in the inference pattern, so as const tuples always yield false. The third is writing the recursion so that it is not in tail position, for example by wrapping the recursive call in another type, which makes long tuples hit the instantiation depth limit. The fourth is expecting Includes to see through object structure: two object types with the same properties but different modifiers are not equal, and that is the point of the test, not a bug.

When not to use this

If the tuple is a list of string or number literals and you only want to check one value, the indexed union is enough: "admin" extends (typeof roles)[number] gives the same answer for literals with far less machinery. Reach for the recursive version when elements are unions, object types, or boolean, where assignability and identity differ. For very long lists, consider whether a union type fits the problem better, since unions are checked as sets and avoid recursion entirely.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.