Testing your types

Advanced · 7 min

Runtime tests can't see a wrong type. Type tests can: @ts-expect-error for code that must fail, expectTypeOf in Vitest or expect-type, and tsd.

Before thisWhy generics, and generic functionsConditional typesReading and debugging type errors

Dev Leonardo · 7 min

Testing your types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Dev LeonardoReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A runtime test checks values, so it passes even when a function's inferred type is `any` or too wide; when the types are part of what you ship, they need tests of their own.
  • A type test is code the compiler checks and nobody runs: it passes when `tsc` reports no errors and fails when it reports one.
  • `// @ts-expect-error` turns a line into a negative test, because the directive itself errors when the line below it compiles.
  • Assigning a result to an annotated variable only proves assignability, which `any` always passes; an exact-equality check such as `expectTypeOf(x).toEqualTypeOf<T>()` catches it.
  • Vitest ships `expectTypeOf` from the expect-type library and type-checks `*.test-d.ts` files when run with `--typecheck`, so type tests sit beside runtime tests in the same runner.
  • `tsd` checks a package's published declaration files from `*.test-d.ts` files using `expectType`, `expectAssignable`, and `expectError`.

A test suite that can’t see types

Here’s a small generic helper and a runtime test for it:

export function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  const out = {} as Pick<T, K>;
  for (const key of keys) out[key] = obj[key];
  return out;
}

// pick.test.ts
test("pick copies the chosen keys", () => {
  const user = { id: 1, name: "Ada", admin: true };
  expect(pick(user, ["id", "name"])).toEqual({ id: 1, name: "Ada" });
});

Now someone simplifies the signature to pick(obj: object, keys: string[]): any. The runtime test still passes; the values are identical. But every caller just lost autocomplete, typo checking, and the guarantee that admin isn’t on the result. For an app, that’s a slow leak. For a library, the types are half of what you ship.

Runtime tests check values. Types are erased before tests run, so a type needs a test the compiler runs. A type test is a file of assertions that tsc checks and nothing executes: zero errors means pass, any error means fail.

@ts-expect-error as a negative test

Some of the most important behavior of a type is what it rejects. You already know the tool from debugging type errors:

const user = { id: 1, name: "Ada", admin: true };

// @ts-expect-error: "email" is not a key of user
pick(user, ["email"]);

const picked = pick(user, ["id"]);
// @ts-expect-error: admin was not picked
picked.admin;

While pick rejects these lines, the directives are satisfied. If pick loosens and the line compiles, the directive itself fails with TS2578: Unused '@ts-expect-error' directive. It’s a smoke detector that alarms when the smoke stops.

One caution: it accepts any error on that line. A typo in the test can produce an unrelated error and keep it green, so keep each expected-error line short and add a reason after the colon.

Positive tests need equality, not assignment

The obvious positive test is an annotated variable:

const result: { id: number; name: string } = pick(user, ["id", "name"]);

That proves assignability, not equality. If pick returned any, this would still compile, and so would a result with extra properties. The test passes in exactly the case it should catch.

What you want is “these two types are identical”. You can build that check from conditional types:

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;

type PickedUser = ReturnType<typeof pick<typeof user, "id" | "name">>;
type Case = Expect<Equal<PickedUser, { id: number; name: string }>>;

The odd-looking Equal compares two generic function types, which forces the checker to require identical types rather than mutually assignable ones, so any doesn’t slip through. You’ll see this pair in type-challenge repositories. For real projects, a library does the same job with readable errors.

expect-type and Vitest’s expectTypeOf

The expect-type library wraps equality checks in a fluent API:

import { expectTypeOf } from "expect-type";

expectTypeOf(pick(user, ["id", "name"])).toEqualTypeOf<{ id: number; name: string }>();
expectTypeOf(pick(user, ["id"])).not.toHaveProperty("admin");
expectTypeOf(user).toExtend<{ id: number }>();

toEqualTypeOf demands an exact match, toExtend checks assignability when that’s what you mean (older code calls it toMatchTypeOf), helpers like .parameter(0) and .returns reach into function types, and .not inverts any assertion.

Vitest ships the same expectTypeOf, plus a looser assertType, so type tests can live in your existing runner:

// pick.test-d.ts
import { expectTypeOf, test } from "vitest";
import { pick } from "./pick";

test("pick narrows the result to the chosen keys", () => {
  const user = { id: 1, name: "Ada", admin: true };
  expectTypeOf(pick(user, ["id", "name"])).toEqualTypeOf<{ id: number; name: string }>();

  // @ts-expect-error: "email" is not a key of user
  pick(user, ["email"]);
});

The important part is the flag. At runtime expectTypeOf does nothing, so without type checking these assertions are never actually checked. Run vitest --typecheck, or set typecheck.enabled in the config, and Vitest runs the type checker over *.test-d.ts files and reports each type error as a failing test. Add that to CI next to your runtime tests.

tsd: testing what you publish

tsd comes from the same need with a library author’s angle. It checks the declaration files your package actually ships, the .d.ts that package.json points at, as a consumer would see them:

// index.test-d.ts
import { expectType, expectError } from "tsd";
import { pick } from ".";

const user = { id: 1, name: "Ada", admin: true };
expectType<Pick<typeof user, "id" | "name">>(pick(user, ["id", "name"]));
expectError(pick(user, ["email"]));

Run npx tsd from the package root. expectType is strict, requiring an identical type, while expectAssignable is the loose version. Because it tests the built output, tsd catches mistakes in declaration emit or a wrong types field that source-level tests miss, which ties into publishing a typed library. It bundles its own TypeScript build, so check which version it uses before trusting a result on a brand-new language feature.

What to test

Test types where inference does real work: generic helpers, overloads, types built from other types, and anything you publish. Don’t write type tests for const x: number = 1. If a type is a plain annotation, the compiler already checks it everywhere it’s used.

About the video

Leonardo, a TanStack Form maintainer, shows how the TanStack libraries unit-test their types: asserting inferred types, testing types in isolation, and running type tests locally and in CI with Vitest’s expectTypeOf and type checking. It’s six minutes and recent. It doesn’t spend long on tsd or @ts-expect-error; the Benny Code video in the links covers @ts-expect-error in depth.

Check yourself

  1. 01Why can a runtime test for a generic `pick` function pass even though its return type is broken?

    The test compares values at runtime, and the values are right. If the return type were `any`, or wider than it should be, the test can't see that, because types are erased before tests run. Only the compiler can check the type.

  2. 02How does `@ts-expect-error` work as a negative test?

    It suppresses an error on the next line, and if there is no error to suppress it reports `Unused '@ts-expect-error' directive`. So `// @ts-expect-error` above `pick(user, ["email"])` passes while the call is rejected, and fails the type check the moment the function starts accepting invalid keys.

  3. 03Why is `const result: { id: number } = pick(user, ["id"]);` a weak type test?

    It only proves the result is assignable to `{ id: number }`. A result typed `any`, or one with extra properties, is assignable too, so the test passes in exactly the cases it should catch. An equality assertion like `toEqualTypeOf` fails unless the types match exactly.

  4. 04What does Vitest need to actually check `expectTypeOf` assertions?

    Type checking has to be on, with `vitest --typecheck` or `typecheck.enabled` in the config. At runtime `expectTypeOf` does nothing, so without type checking a wrong assertion still passes. With it on, Vitest runs the type checker over files like `*.test-d.ts` and reports each error as a failing test.

  5. 05What does `tsd` test that an in-repo `expectTypeOf` test might not?

    `tsd` checks the declaration files your package actually publishes, the `.d.ts` that `package.json` points to, from the point of view of a consumer importing the package. That catches problems introduced by declaration emit or a wrong `types` field, which tests against source files wouldn't see.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark