Vitest 29 🧪 Type Testing — expectTypeOf and –typecheck
A test suite that only checks runtime behavior is half a test suite. The TypeScript compiler already verifies types when the project is built, but a build is a coarse check: it tells you the project compiles, not that a specific function returns a specific type. Type testing fills that gap. It is the practice of writing assertions about types themselves — that getUser() returns Promise<User> and not Promise<User | null>, that pick infers the right shape, that a generic helper preserves the caller’s type argument.
Vitest ships two pieces for this. The first is expectTypeOf, a runtime API whose assertions are type-level: the calls exist at runtime but do nothing, and the real checking happens in the editor and in the compiler. The second is the --typecheck mode, which runs tsc or vue-tsc over the type tests and fails the run when the types do not match. The two pieces are independent — expectTypeOf gives you editor feedback and compile-time errors, and --typecheck gives you a CI gate — and the sections below cover both, along with the config that wires them together.
Key point: Type tests are ordinary .test-d.ts files whose assertions are checked by the TypeScript compiler, not by Vitest’s runtime; expectTypeOf provides the assertion API, and --typecheck runs the compiler over those files so a type regression fails CI the same way a runtime regression does.
Why type testing exists
The compiler is not a test. A successful tsc --noEmit proves the project has no type errors. It does not prove that parseConfig() returns Config rather than unknown, because a function that returns unknown compiles fine. The compiler checks consistency, not intent, and type testing is how you assert intent.
Types are part of the public API. A library’s exported function signature is a contract. If a refactor changes getUsers(): User[] to getUsers(): Promise<User[]>, the compiler may still accept every internal call site while breaking every consumer. A type test that pins the return type catches the change at the point of the refactor, not at the point of the consumer’s bug report.
Inference is invisible without assertions. A generic helper like groupBy infers its return type from the callback. The inference is easy to get subtly wrong — a widened literal, a dropped readonly, a collapsed union — and the wrong inference compiles cleanly. expectTypeOf is how you freeze the inferred type and notice when it drifts.
Runtime tests cannot see types. A test that calls getUser() and asserts on the resolved value runs after the type is erased. It can never tell you whether the return type was User or any, because both behave identically at runtime. Type testing is the only layer that observes types as types.
The editor is a test runner. expectTypeOf assertions produce red squiggles in the editor the moment a type mismatches, before any command is run. That immediacy is the point: the feedback loop for a type error is the keystroke, not the CI run.
The trade-off. Type tests are slower to write than runtime tests, and they do not run in the browser or in a deployed environment. They are a development-time and CI-time tool, and the cost is worth paying for the code that other code depends on — libraries, shared utilities, public APIs — and usually not worth paying for leaf components whose types are consumed in one place.
a. The .test-d.ts file and expectTypeOf
A type test lives in a file with the .test-d.ts suffix. Vitest treats the suffix as a type-test marker: the file is collected by the typechecker rather than executed as a normal runtime test. The assertions come from expectTypeOf, which is imported from vitest like any other API.
// src/user.test-d.ts
import { expectTypeOf, test } from "vitest";
import { getUser } from "./user";
test("getUser returns a User", () => {
// The assertion is type-level: it checks the return type
// of getUser, not the resolved value
expectTypeOf(getUser).returns.toEqualTypeOf<Promise<User>>();
});
expectTypeOf takes a value or a function and exposes a chain of type-level matchers. The assertion does nothing at runtime — the calls compile to no-ops — but the compiler checks them. If getUser returned Promise<User | null>, the .toEqualTypeOf<Promise<User>>() chain would produce a type error in the editor and in tsc.
The .returns accessor extracts the return type of a function, so the assertion compares the function’s output type directly. Without it, expectTypeOf(getUser).toEqualTypeOf<() => Promise<User>>() would compare the whole function type, which is rarely what you want.
import { expectTypeOf, test } from "vitest";
test("parseConfig returns Config, not unknown", () => {
const parseConfig = (raw: string) => JSON.parse(raw) as Config;
// Compares the full function type, parameter and return
expectTypeOf(parseConfig).toEqualTypeOf<(raw: string) => Config>();
// Compares only the return type
expectTypeOf(parseConfig).returns.toEqualTypeOf<Config>();
});
The first assertion pins the whole signature, parameter type included. The second pins only the output. Both are useful: the full-signature form catches a parameter change, and the return-only form stays valid when the parameter type is refactored but the output contract is unchanged.
b. The expectTypeOf matchers
expectTypeOf provides a family of matchers, each answering a different question about a type. The most useful are the exact-match, assignability, and property matchers, because they cover the three ways a type assertion usually fails.
import { expectTypeOf, test } from "vitest";
test("the matchers", () => {
// Exact equality: the two types must be identical
expectTypeOf<string>().toEqualTypeOf<string>();
// Assignability: the actual type must be assignable to the expected
expectTypeOf<"a" | "b">().toMatchTypeOf<string>();
// Property presence and type
expectTypeOf<{ id: number; name: string }>().toHaveProperty("id");
expectTypeOf<{ id: number }>().toHaveProperty("id").toEqualTypeOf<number>();
// Nullable and undefined checks
expectTypeOf<string | null>().toBeNullable();
expectTypeOf<string>().not.toBeNullable();
});
toEqualTypeOf is the strict matcher. It compares the two types structurally and requires them to be identical, so string and "a" | "b" do not match. toMatchTypeOf is the loose matcher. It asks whether the actual type is assignable to the expected type, which is the right question when you care about a contract rather than an exact shape. A "a" | "b" is assignable to string, so the loose matcher accepts it while the strict one rejects it.
The .not modifier negates any matcher, and the negation runs through the same type-level machinery. expectTypeOf<string>().not.toBeNullable() fails if the type is nullable, which is how a nullable regression gets caught.
test("inference is preserved", () => {
const users = [{ id: 1, name: "Alice" }];
// The array element type is inferred, and we assert on it
expectTypeOf(users).toEqualTypeOf<{ id: number; name: string }[]>();
// A widened literal would fail the strict matcher
const roles = ["admin", "user"] as const;
expectTypeOf(roles).toEqualTypeOf<readonly ["admin", "user"]>();
});
The second assertion is the one that catches a real regression. If a refactor removes as const, the type widens to string[], the strict matcher fails, and the change is caught. A runtime test on roles would still pass, because the values are unchanged.
c. The –typecheck mode and its config
The expectTypeOf assertions are checked by the compiler whenever the file is opened or the project is built. The --typecheck flag is what runs the compiler over the type-test files as part of the test run, so a type regression fails the same command that runs the runtime tests.
# Run the type tests as part of the suite
vitest --typecheck
# Type tests only, skipping the runtime tests
vitest --typecheck.only
The flag is configured in vitest.config.ts under test.typecheck. The include pattern points at the .test-d.ts files, and the checker option selects the compiler: tsc for plain TypeScript, vue-tsc for Vue SFCs.
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
typecheck: {
// The files the typechecker will run over
include: ["**/*.test-d.ts"],
// "tsc" for TypeScript, "vue-tsc" for Vue projects
checker: "tsc",
// The tsconfig the checker uses for the type tests
tsconfig: "./tsconfig.json",
},
},
});
The tsconfig option matters because the type tests may need a different lib or strict setting than the application code. A strict type test against a non-strict tsconfig produces different results than the same test against a strict one, and pinning the config makes the check reproducible.
The expectTypeOf import also changes under typecheck. The vitest package re-exports expectTypeOf, but the @vitest/expect package provides the same API with the typechecker’s diagnostics attached. For most projects the vitest import is sufficient; the direct import is the escape hatch when the editor’s diagnostics do not appear.
// The standard import, re-exported by vitest
import { expectTypeOf } from "vitest";
// The direct import, useful when editor diagnostics are missing
import { expectTypeOf } from "@vitest/expect";
The two imports expose the same matchers. The vitest re-export is the recommended form because it keeps the import surface small and matches the rest of the test file’s imports.
Complete Example Session
// ============================================
// PART 1: THE FUNCTION UNDER TEST
// ============================================
// src/user.ts
export interface User {
id: number;
name: string;
}
export async function getUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json() as Promise<User>;
}
// ============================================
// PART 2: THE TYPE TEST FILE
// ============================================
// src/user.test-d.ts
import { expectTypeOf, test } from "vitest";
import { getUser, type User } from "./user";
test("getUser returns a User", () => {
// The strict matcher pins the exact return type
expectTypeOf(getUser).returns.toEqualTypeOf<Promise<User>>();
});
// ============================================
// PART 3: THE ASSIGNABILITY MATCHER
// ============================================
test("User is assignable to a record", () => {
// The loose matcher asks only for assignability
expectTypeOf<User>().toMatchTypeOf<Record<string, unknown>>();
});
// ============================================
// PART 4: THE PROPERTY MATCHER
// ============================================
test("User has an id", () => {
// Property presence and its type
expectTypeOf<User>().toHaveProperty("id").toEqualTypeOf<number>();
});
// ============================================
// PART 5: THE NEGATION
// ============================================
test("User is not nullable", () => {
// The .not modifier catches a nullable regression
expectTypeOf<User>().not.toBeNullable();
});
// ============================================
// PART 6: THE GENERIC INFERENCE
// ============================================
function groupBy<T, K extends keyof T>(items: T[], key: K): Map<T[K], T[]> {
const map = new Map<T[K], T[]>();
for (const item of items) {
const k = item[key];
map.set(k, [...(map.get(k) ?? []), item]);
}
return map;
}
test("groupBy infers the key type", () => {
const users: User[] = [];
// The inferred Map key type must be the property type
expectTypeOf(groupBy(users, "id")).toEqualTypeOf<Map<number, User[]>>();
});
// ============================================
// PART 7: THE CONST ASSERTION
// ============================================
test("roles stay readonly", () => {
const roles = ["admin", "user"] as const;
// Removing `as const` widens the type and fails this test
expectTypeOf(roles).toEqualTypeOf<readonly ["admin", "user"]>();
});
// ============================================
// PART 8: THE CONFIG
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
typecheck: {
include: ["**/*.test-d.ts"],
checker: "tsc",
tsconfig: "./tsconfig.json",
},
},
});
// ============================================
// PART 9: THE COMMAND
// ============================================
// vitest --typecheck → runtime tests plus type tests
// vitest --typecheck.only → type tests only
// ============================================
// PART 10: THE REGRESSION
// ============================================
// If getUser is refactored to return Promise<User | null>,
// the strict matcher in PART 2 fails, while every runtime
// test that awaits getUser() still passes.
The parts covered the function under test, the type-test file, the assignability and property matchers, the negation modifier, generic inference, a const-assertion regression, the typecheck config, the command, and the regression the whole setup is designed to catch.
Quick Reference
The Typecheck Options
| Option | Value | Effect |
|---|---|---|
include | ["**/*.test-d.ts"] | Files the checker runs over |
checker | "tsc" / "vue-tsc" | Compiler that runs the check |
tsconfig | "./tsconfig.json" | Config the checker uses |
--typecheck | CLI flag | Runtime tests plus type tests |
--typecheck.only | CLI flag | Type tests only |
The Matchers
| Matcher | Question |
|---|---|
toEqualTypeOf | Are the types exactly equal? |
toMatchTypeOf | Is the actual assignable to the expected? |
toHaveProperty | Does the type have the property? |
toBeNullable | Is the type nullable? |
.not | Negates any matcher |
The Accessors
| Accessor | Extracts |
|---|---|
.returns | The return type of a function |
.parameters | The parameter tuple of a function |
.resolves | The resolved type of a promise |
.items | The element type of an array |
The File Suffix
| Suffix | Meaning |
|---|---|
.test.ts | Runtime test, executed |
.test-d.ts | Type test, checked by the compiler |
Best Practices
✅ Do This:
// Use the .test-d.ts suffix for type tests
// src/user.test-d.ts // ✅
// Use the strict matcher for a public contract
expectTypeOf(getUser).returns.toEqualTypeOf<Promise<User>>(); // ✅
// Use the loose matcher for assignability
expectTypeOf<User>().toMatchTypeOf<Record<string, unknown>>(); // ✅
// Assert on inference, not just on declarations
expectTypeOf(groupBy(users, "id")).toEqualTypeOf<Map<number, User[]>>(); // ✅
// Pin the tsconfig for reproducible checks
typecheck: { tsconfig: "./tsconfig.json" } // ✅
❌ Don’t Do This:
// Put type assertions in a runtime .test.ts file
// src/user.test.ts // ❌
// Use `any` to silence a matcher failure
expectTypeOf(getUser).returns.toEqualTypeOf<any>(); // ❌
// Use the strict matcher on a widened literal
expectTypeOf(["admin"]).toEqualTypeOf<readonly ["admin"]>(); // ❌ (widens)
// Rely on the editor alone in CI
// (no `--typecheck` in the pipeline) // ❌
// Skip the tsconfig option and inherit the wrong strictness
typecheck: { include: ["**/*.test-d.ts"] } // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Type test not run | File named .test.ts | Rename to .test-d.ts |
| Strict matcher fails on a literal | Array widened to string[] | Add as const |
| Editor shows no error | Wrong import path | Import from vitest |
| Check passes locally, fails in CI | Different tsconfig | Pin tsconfig option |
| Generic inference untested | Only declarations asserted | Assert on call results |
| Type regression slips through | No --typecheck in CI | Add the flag to the pipeline |
Real-World Examples
1. Return type contract
expectTypeOf(getUser).returns.toEqualTypeOf<Promise<User>>();
2. Assignability
expectTypeOf<User>().toMatchTypeOf<Record<string, unknown>>();
3. Property type
expectTypeOf<User>().toHaveProperty("id").toEqualTypeOf<number>();
4. Non-nullable
expectTypeOf<User>().not.toBeNullable();
5. Generic inference
expectTypeOf(groupBy(users, "id")).toEqualTypeOf<Map<number, User[]>>();
6. Const assertion
expectTypeOf(roles).toEqualTypeOf<readonly ["admin", "user"]>();
7. Parameter types
expectTypeOf(getUser).parameters.toEqualTypeOf<[number]>();
8. Resolved type
expectTypeOf(getUser).resolves.toEqualTypeOf<User>();
9. Typecheck config
test: { typecheck: { include: ["**/*.test-d.ts"], checker: "tsc" } }
10. CLI flag
// vitest --typecheck
Visual
The Two Test Layers
┌─────────────────────────────────────────────────────────┐
│ RUNTIME TESTS TYPE TESTS │
│ .test.ts .test-d.ts │
│ │
│ executed by Vitest checked by tsc │
│ asserts values asserts types │
│ fails at runtime fails at compile time │
│ │
│ vitest vitest --typecheck │
└─────────────────────────────────────────────────────────┘
The Matcher Decision
┌─────────────────────────────────────────────────────────┐
│ WHAT DO YOU WANT TO ASSERT? │
│ │
│ exact type ──────────► toEqualTypeOf<T>() │
│ │
│ assignable to ───────► toMatchTypeOf<T>() │
│ │
│ has a property ──────► toHaveProperty("key") │
│ │
│ is nullable ─────────► toBeNullable() │
│ │
│ any of the above ────► .not.<matcher>() │
└─────────────────────────────────────────────────────────┘
The Accessor Chain
┌─────────────────────────────────────────────────────────┐
│ expectTypeOf(fn) │
│ │ │
│ ├── .returns ──────► the return type │
│ ├── .parameters ───► the parameter tuple │
│ ├── .resolves ─────► the resolved type │
│ └── .items ────────► the element type │
│ │
│ expectTypeOf(fn).returns.toEqualTypeOf<Promise<User>>()│
└─────────────────────────────────────────────────────────┘
The Regression Flow
┌─────────────────────────────────────────────────────────┐
│ BEFORE │
│ getUser(): Promise<User> │
│ type test passes ──────────► green │
│ │
│ REFACTOR │
│ getUser(): Promise<User | null> │
│ │
│ AFTER │
│ runtime tests pass ────────► green (values unchanged) │
│ type test fails ───────────► red (type changed) │
│ │
│ The regression is caught at the type layer. │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Type-test suffix | .test-d.ts |
| Assertion API | expectTypeOf |
| Strict matcher | toEqualTypeOf |
| Loose matcher | toMatchTypeOf |
| Negation | .not |
| CLI flag | --typecheck |
| Type-only flag | --typecheck.only |
| Compiler option | checker: "tsc" / "vue-tsc" |
| Config section | test.typecheck |
| Return accessor | .returns |
| Parameter accessor | .parameters |
Key takeaways:
- Type tests are compiler tests, not runtime tests. A
.test-d.tsfile is checked bytsc, and the assertions are type-level. The calls compile to no-ops at runtime, and the real check happens in the editor and intsc. - The matcher choice is the assertion’s meaning.
toEqualTypeOfrequires an exact match, andtoMatchTypeOfasks only for assignability. The strict matcher catches a widened literal or a droppedreadonly; the loose matcher catches a broken contract. --typecheckis the CI gate. The flag runs the compiler over the type-test files as part of the test run, so a type regression fails the same command that runs the runtime tests. Without it, the type tests are editor-only.- Pin the tsconfig. The
typecheck.tsconfigoption makes the check reproducible, because a strict type test against a non-strict config produces different results than the same test against a strict one. - Assert on inference, not just on declarations. A generic helper’s inferred type is easy to get subtly wrong, and a type test on the call result —
expectTypeOf(groupBy(users, "id"))— is what freezes the inference.
Remember: Type testing is the layer that observes types as types. The .test-d.ts suffix marks the file, expectTypeOf provides the matchers, and --typecheck runs the compiler so a type regression fails CI. Use the strict matcher for public contracts, the loose matcher for assignability, and assert on inference wherever a generic helper is involved. The compiler already checks consistency; type tests check intent, and intent is what a refactor silently changes.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!