Sub topic 13
Testing type utilities with compile-time assertions
Type-level code has no runtime, so ordinary unit tests can't check it. A Reverse type that returns the wrong tuple compiles without complaint until some caller depends on it. This chapter shows how to turn a type-level result into a compile-time assertion, so tsc fails when a utility is wrong.
This chapter assumes you know generics, conditional types with infer, and the recursive utilities from earlier chapters, such as Reverse and UnionToIntersection. You also need to be able to run tsc from the command line.
The idea: make wrong types a compile error
A type test has three parts:
- A type that evaluates to
truewhen two types are the same, and tofalseotherwise. - A type that accepts only
true, so any other argument produces an error. - A command that type-checks the test file, such as
tsc --noEmit.
Here is the pair of helpers:
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
type Expect<T extends true> = T;Expect<T extends true> is a constrained alias. Expect<true> is fine. Expect<false> is an error, because false does not satisfy extends true. Putting Equal inside Expect gives you an assertion.
type Reverse<T extends unknown[], Acc extends unknown[] = []> =
T extends [infer Head, ...infer Rest]
? Reverse<Rest, [Head, ...Acc]>
: Acc;
type _Test1 = Expect<Equal<Reverse<[1, 2, 3]>, [3, 2, 1]>>;This file compiles. If you change the expected tuple to [1, 2, 3], the compiler reports that false does not satisfy the constraint true. The error appears at the exact line of the failing assertion.
Why Equal looks so strange
A simpler definition seems obvious: two types are equal if each is assignable to the other. That version breaks in several cases.
type NaiveEqual<X, Y> = [X] extends [Y] ? ([Y] extends [X] ? true : false) : false;
type T1 = NaiveEqual<any, 1>;
// true, which is wrong. any is assignable in both directions.
type T2 = NaiveEqual<{ a: 1 } & { b: 2 }, { a: 1; b: 2 }>;
// true. This is arguably fine for assignability, but the two types are not identical.Assignability is a different question from identity. The any case is the one that causes silent failures. A utility that wrongly returns any would pass a naive test against every expected type.
The Equal helper avoids this by comparing two generic function types. Each function returns a conditional type that is deferred, because it depends on the unresolved type parameter T. When the compiler checks whether one deferred conditional type is assignable to the other, it requires the extends types to be identical. It does not accept merely compatible types. This uses the compiler's internal identity check, and the language specification does not document it. The trick is widely used, including by the type-challenges project, but a future compiler release could in principle change its edge cases.
The unconstrained T also stops the conditional types from distributing over unions in X or Y. Distribution only happens when the checked type is a naked type parameter that gets instantiated, and here the deferred conditional is never instantiated.
What Equal says about common cases
These are worth memorizing because they produce the most surprising test failures.
| Comparison | Result | Reason | Column | Column |
|---|---|---|---|---|
| `Equal<1 \ | 2, 2 \ | 1>` | `true` | Unions are unordered |
| `Equal<never, never>` | `true` | `never` is handled without distribution | ||
| `Equal<any, 1>` | `false` | `any` is not identical to `1` | ||
| `Equal<{ a: 1 } & { b: 2 }, { a: 1; b: 2 }>` | `false` | An intersection is a different type from the merged object | ||
| `Equal<readonly [1], [1]>` | `false` | Readonly modifiers matter | ||
| `Equal<{ a?: 1 }, { a: 1 \ | undefined }>` | `false` | Optional and required properties differ |
The intersection row catches people most often. A utility such as UnionToIntersection really does return an intersection, so you test it against an intersection.
type UnionToIntersection<U> =
(U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void
? I
: never;
type _Test2 = Expect<
Equal<UnionToIntersection<{ a: 1 } | { b: 2 }>, { a: 1 } & { b: 2 }>
>;If you want to compare against a flat object, flatten the result first with a small helper.
type Simplify<T> = { [K in keyof T]: T[K] };
type _Test3 = Expect<
Equal<Simplify<UnionToIntersection<{ a: 1 } | { b: 2 }>>, { a: 1; b: 2 }>
>;Simplify is a mapped type over keyof T. It rebuilds the intersection as a single object type. Use it only in the test, so the helper doesn't become part of the utility's public result.
Testing that something does not match
Sometimes you want to prove that two types differ. There are two ways.
The first is a Not helper:
type Not<B extends boolean> = B extends true ? false : true;
type _Test4 = Expect<Not<Equal<any, string>>>;The second is the @ts-expect-error comment, which asserts that the next line contains a compile error. This is the right tool for checking that a utility rejects bad input through its constraints.
type Head<T extends unknown[]> = T extends [infer H, ...unknown[]] ? H : never;
// @ts-expect-error Head only accepts arrays
type _Test5 = Head<string>;
// @ts-expect-error the assertion is wrong, so Expect reports an error
type _Test6 = Expect<Equal<Head<[1, 2]>, 2>>;If the next line compiles cleanly, TypeScript reports "Unused '@ts-expect-error' directive". That makes the negative test fail when the code stops erroring, which is the behavior you want. Prefer @ts-expect-error over @ts-ignore in tests, because @ts-ignore stays silent in both cases.
A worked example: catching a subtle bug
Suppose someone changes the accumulator order in Reverse while refactoring.
type BadReverse<T extends unknown[], Acc extends unknown[] = []> =
T extends [infer Head, ...infer Rest]
? BadReverse<Rest, [...Acc, Head]>
: Acc;
type _Test7 = Expect<Equal<BadReverse<[1, 2, 3]>, [3, 2, 1]>>;[...Acc, Head] appends each element instead of prepending it, so the type simply returns the input order. The assertion fails and the error points at _Test7.
The edge cases of a utility deserve tests too, and often they matter more than the main case. For a recursive type, check the base case and the smallest input.
type _Test8 = Expect<Equal<Reverse<[]>, []>>;
type _Test9 = Expect<Equal<Reverse<[1]>, [1]>>;
type _Test10 = Expect<Equal<Reverse<[1, 'a', true]>, [true, 'a', 1]>>;For a distributive utility, test a union input. For one that unwraps, test an input that needs no unwrapping.
type ElementType<T> = T extends (infer U)[] ? U : never;
type _Test11 = Expect<Equal<ElementType<string[] | number[]>, string | number>>;
type _Test12 = Expect<Equal<ElementType<number>, never>>;
type _Test13 = Expect<Equal<ElementType<never>, never>>;The last line checks that ElementType<never> is never. A distributive conditional type applied to never produces never, because there are no union members to map over.
Running the tests
Keep the assertions in a file that is only type-checked, such as types.test.ts or utils.type-test.ts. Nothing in the file has to run. All the declarations are types, so the compiled output is empty.
{
"compilerOptions": {
"strict": true,
"noEmit": true,
"noUnusedLocals": false,
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler"
},
"include": ["src/**/*.ts"]
}Run npx tsc -p . in CI. Any failing assertion makes the command exit with a non-zero status.
The diagram below shows the workflow.
Existing libraries
You do not have to maintain your own helpers. Several tools provide the same capability with friendlier error messages:
expect-typeoffers a fluent API such asexpectTypeOf<T>().toEqualTypeOf<U>().- Vitest includes
expectTypeOfand can run type tests in a separate mode. tsdchecks.test-d.tsfiles against a package's published types.
The hand-written Equal and Expect pair is still worth knowing. It has no dependencies, it shows what the libraries do under the hood, and it fits into any project in a few lines.
Common mistakes
- Comparing against
anyby accident. If an expected type is accidentallyany,Equalisfalse, which is useful. If you used the naive mutual-assignability check, it would pass. - Forgetting
readonly. A utility such asDeepReadonlyshould be compared against an expected type that is alsoreadonlyat every level. - Testing only the happy path. Include
never, empty tuples, unions and non-matching inputs. - Reading a long error. When
Expectfails, the message mentionsfalseandtrue. To see the actual result, hover over a plain alias such astype Actual = Reverse<[1, 2, 3]>, or assign it to a variable of an incompatible type to print it.
Exercise
Write a Last utility that returns the last element of a tuple, using infer and a rest element at the front. Then write three assertions with Expect and Equal: one for Last<[1, 2, 3]>, one for the empty tuple, and one that uses @ts-expect-error to show that a wrong expectation is rejected.
Show answer
type Last<T extends unknown[]> = T extends [...unknown[], infer L] ? L : never; type L1 = Expect<Equal<Last<[1, 2, 3]>, 3>>; type L2 = Expect<Equal<Last<[]>, never>>; // @ts-expect-error the last element is 3, not 1 type _L3 = Expect<Equal<Last<[1, 2, 3]>, 1>>; The empty tuple does not match the pattern, so the false branch gives never. The directive passes because the next line contains an error, and it would fail if the line compiled.
Exercise
Why does Equal<{ a: 1 } & { b: 2 }, { a: 1; b: 2 }> evaluate to false, and how can you still test a utility that returns an intersection?
Show answer
Equal checks that two types are identical, and an intersection of two object types is not the same type as a single merged object, even though they are mutually assignable. Either compare against the intersection itself, or wrap the actual result in a Simplify mapped type such as { [K in keyof T]: T[K] } and compare the flattened result with the merged object.