Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 96 ยท TypeScript in Practice

Testing Types

Write tests for TypeScript types themselves with Equal and Expect helpers, @ts-expect-error, Vitest expectTypeOf, tsd and type-level regression tests for utility types and library APIs.

Most tests check what code does when it runs. But sometimes the product is a type: a utility type your team shares, the public API of a library, a generic function whose return type must be exact. A regression there has no runtime symptom. A refactor can quietly turn a precise type into any, and every test still passes. To guard against that, you test the types themselves.

This lesson shows three layers of type testing: plain TypeScript with an Equal helper and @ts-expect-error, Vitest's expectTypeOf, and the tsd tool. It builds on Testing TypeScript with Jest and Vitest and the type-level techniques from Recursive Types and Type-Level Programming.

The idea: a type test is a compile-time check

A type test is a piece of code that only has to compile. If the type is right, tsc stays quiet; if someone breaks the type, tsc reports an error and CI fails. The test never needs to run. This is a different failure mode from ordinary tests:

flowchart LR
  A["Change a type"] --> B["tsc --noEmit"]
  B -->|"assertion still holds"| C["No error: pass"]
  B -->|"assertion broken"| D["Compile error: fail"]

Type tests pass or fail at compile time, so they run with the type checker, not with a test runner.

Because they fail at compile time, run tsc --noEmit in CI (the earlier lesson called this out too). A test runner that strips types, such as Vitest or Node's built-in TypeScript support, won't notice a broken type assertion on its own.

Building blocks without any library

You don't need a package to start. Three small helpers cover most assertions:

TypeScript
// True only when X and Y are exactly the same type
type Equal<X, Y> =
  (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;

// Compile error unless the argument is exactly `true`
type Expect<T extends true> = T;

// Compile error unless the argument is exactly `false`
type ExpectNot<T extends false> = T;

Why the strange Equal? A simpler X extends Y check only tests assignability, and any, optional properties and readonly modifiers slip through it. The nested-generic form compares the two types as identical, which is the check you almost always want. You write assertions by using the helper as a type alias that must satisfy Expect:

TypeScript
type Check1 = Expect<Equal<ReturnType<() => string>, string>>;

If the two types differ, Equal gives false, which isn't assignable to true, so the line fails to compile. Let's use it on real utility types.

TypeScript Assertions with Equal and Expect (compile-time only)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The array of Expect<...> types is a handy pattern: every test is one element, and the compiler reports the exact element that fails. The last line only exists to print something, since the assertions themselves produce no output. Change Draft['email'] to string and the file stops compiling (try it in the editor to see the message).

Asserting that something is an error

Sometimes the test is "this must not compile". Maybe a function must reject the wrong argument. The comment directive // @ts-expect-error marks the next line as an expected error, and fails if the line has no error:

TypeScript
function setLevel(level: 'debug' | 'info' | 'error'): void {}

setLevel('info'); // fine

// @ts-expect-error - 'verbose' is not a valid level
setLevel('verbose');

If a later change makes setLevel accept any string, the second call becomes valid, the directive is unused, and tsc reports "Unused '@ts-expect-error' directive". That's your regression alarm. Prefer @ts-expect-error over @ts-ignore in tests, because @ts-ignore stays silent when the error disappears.

Keep each expected error on its own line with a short reason, and keep the code under the directive minimal. A directive covers the whole next line, so a long line with two mistakes would pass even if one of them stopped being an error.

TypeScript @ts-expect-error documents what must be rejected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The two bad calls are known compile errors, and the directives acknowledge them, so the file type-checks. The program still runs, though, because the types are erased: the unknown currency happily prints, and the string amount fails only when JavaScript tries to call toFixed on it. It prints:

TEXT
12.50 USD
1200 JPY
9.99 GBP
runtime error: amount.toFixed is not a function

That gap is the reason type tests exist: the compiler caught both calls before the program ran, and the directives lock that behavior in.

expectTypeOf in Vitest

Vitest ships a fluent assertion API for types called expectTypeOf (built on the expect-type library). It reads like ordinary test code and gives better error messages than hand-rolled helpers:

TypeScript
import { expectTypeOf, test } from 'vitest';
import { first, pick } from './collections';

test('first() returns the element type or undefined', () => {
  expectTypeOf(first([1, 2, 3])).toEqualTypeOf<number | undefined>();
  expectTypeOf(first(['a'])).toEqualTypeOf<string | undefined>();
});

test('pick() only accepts real keys', () => {
  const user = { id: 1, name: 'Ada' };
  expectTypeOf(pick(user, ['name'])).toEqualTypeOf<{ name: string }>();
  // @ts-expect-error - 'email' is not a key of user
  pick(user, ['email']);
});

test('function shapes', () => {
  expectTypeOf(first).parameters.toEqualTypeOf<[readonly unknown[]]>();
  expectTypeOf(first).returns.not.toBeAny();
});

Common matchers: toEqualTypeOf<T>() (exact), toMatchTypeOf<T>() (assignable), toBeString(), toBeNumber(), toBeAny(), toBeNever(), toBeUndefined(), toBeCallableWith(...), plus .parameters, .returns, .parameter(n) and .items to drill into functions and arrays. Chain .not to invert: expectTypeOf<string>().not.toEqualTypeOf<number>().

One important detail: at runtime expectTypeOf does nothing and always passes. The checking happens when tsc (or vitest --typecheck) compiles the file. Vitest's typecheck mode runs the compiler for files named *.test-d.ts, so a common convention is:

TypeScript
// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    typecheck: { enabled: true, include: ['src/**/*.test-d.ts'] },
  },
});

Put type-only tests in *.test-d.ts files, and they run in their own pass with proper reporting.

tsd for library authors

tsd is a standalone tool built for packages that publish type declarations. It checks the public types in your .d.ts output as a consumer would see them. You write files named index.test-d.ts next to the package:

TypeScript
import { expectType, expectError, expectAssignable } from 'tsd';
import { createStore } from '.';

const store = createStore({ count: 0 });

expectType<number>(store.getState().count);
expectAssignable<{ count: number }>(store.getState());
expectError(store.setState({ count: 'nope' }));

Run it with npx tsd; it type-checks those files against the package's declared types and fails the build on any mismatch. Use tsd when you want to test what consumers see (after the build), and expectTypeOf when you're already running Vitest. The ideas are identical: an exact-type check, an assignability check and an expected error.

What to test, and what not to

Type tests are cheap, but they can become noise. Aim them where mistakes are likely and costly:

  • Utility and mapped types you wrote: check a few inputs, including edge cases like empty objects, unions, optional keys and never.
  • Generic functions: that inference picks the narrowest type ('a' | 'b' rather than string) and that bad arguments are rejected.
  • Overloads: one assertion per signature (see Overloads).
  • Public API of a library: a tsd or expectTypeOf suite that locks the types users depend on.
  • Regression for a bug: when someone reports a wrong type, add the failing assertion first.

Skip testing what the compiler already guarantees, such as that a plain interface has the fields you typed. And don't test implementation details of a type, like the exact shape of an intermediate helper; test the observable result.

Always include at least one negative test per important type: an @ts-expect-error or a .not.toEqualTypeOf. A type that accidentally became any makes every positive assertion pass (any is assignable to and from almost everything), but it can't make a negative one pass. This is also why Equal and toEqualTypeOf are stricter than plain assignability.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do type tests need tsc --noEmit in CI?

    Runners like Vitest and Node strip types without checking. Type assertions only fail when the compiler examines the file.
  2. 2. What does // @ts-expect-error do when the next line has no error?

    The directive asserts that an error exists. If the line compiles cleanly, tsc reports "Unused '@ts-expect-error' directive", which is how you catch a type that became too permissive.
  3. 3. Why is Equal<X, Y> better than checking X extends Y?

    Assignability lets many different types pass (any, narrower types, differences in optionality). Equal compares the types for identity, which is what a test usually wants.
  4. 4. What does expectTypeOf(value).toEqualTypeOf<string>() do at runtime?

    expectTypeOf is erased of meaning at runtime; it exists to be examined by the compiler, which is why vitest --typecheck or tsc must run.
  5. 5. Why should every important type have at least one negative test?

    any is compatible with nearly everything, so positive checks can pass for a ruined type. An expected error or a .not assertion catches it.

Summary

  • A type test is code that must compile; it fails when tsc reports an error, so run tsc --noEmit (or vitest --typecheck) in CI.
  • Equal<X, Y> plus Expect<...> gives exact-type assertions with no dependencies.
  • // @ts-expect-error asserts that something is rejected and fails when it stops being an error. Prefer it to @ts-ignore.
  • Vitest's expectTypeOf offers toEqualTypeOf, toMatchTypeOf, .parameters, .returns and .not; use *.test-d.ts files for a dedicated pass.
  • tsd checks the public .d.ts types of a package as a consumer would see them.
  • Test utility types, generic inference, overloads and public APIs, and always add a negative case.

Next: Project: Todo CLI