Skip to content

Compile-Time Contract Tests

The Course
•
25 min study

Runtime tests execute JavaScript after type information is erased. A compile-time contract test instead asks whether valid usage is accepted and known invalid usage is rejected. These tests protect the public type surface when implementations change.

TypeScript's @ts-expect-error comment expects a diagnostic on the next line. If no error remains, the directive itself becomes an unused-directive error. That makes it useful for a deliberately invalid call in a compile-only test file. @ts-ignore does not provide the same unused-directive signal.

Do not use expected-error comments to patch application code or to make a lesson's real error disappear. The project's contracts.ts contains only intentional misuse and is checked by tsc, never executed as a program. The ordinary playground error lab below remains unsuppressed so learners can read the actual diagnostic.

The project does not enable a special framework for type tests. Its normal strict compiler includes contracts.ts. Runtime tests still verify validation, normalization and request ordering; type tests cannot replace them.

Predict, run, and explain

Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.

Predict, then runTypeScript
type Book = { readonly title: string };

function label(book: Book): string {
  return book.title;
}

console.log(label({ title: "Types" }));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types

Read the compiler error

This is a deliberate negative test without suppression, so the real compiler error stays visible.

Find and fix the type errorTypeScript
type Book = { readonly title: string };

const book: Book = { title: "Types" };

book.title = "Changed";

Enable JavaScript to edit and type-check this example.

Check your diagnosis

Readonly prevents assignment through this typed reference. An application should create a changed copy; a compile-only test can retain the invalid line under an expected-error directive.

Protect caller relationships without executing misuse

A negative type test expects a diagnostic on a minimal invalid line. Keep unrelated mistakes off that line so the intended error cannot disappear while another error continues satisfying the directive. Positive calls are equally important: a signature rejecting every caller is not a useful success.

Compile-only invalid code must not become part of the runtime entry. A never-called function in a small playground can demonstrate checking, while the real project uses a separate contract file. A type test cannot prove trimming, error paths or request order.

A negative test for a wrong argumentTypeScript
type Book = { readonly title: string };

function label(book: Book): string {
  return book.title;
}

function negative(): void {
  // @ts-expect-error the caller must provide a string title
  label({ title: 25 });
}

console.log(label({ title: "Types" }));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types

The invalid call is checked but never executed. If label becomes too permissive, the directive must become unused and fail the checker.

A negative test for readonlyTypeScript
type Book = { readonly title: string };

function negative(book: Book): void {
  // @ts-expect-error readonly is part of the caller contract
  book.title = "Changed";
}

const book: Book = { title: "Types" };

console.log(book.title);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types

The example protects assignment permissions separately from runtime freezing. No invalid mutation is executed just to demonstrate the compiler constraint.

Try the rule on new inputs

Temporarily remove readonly and confirm the unused-directive error. Separately remove runtime normalization and confirm only the behavior suite catches it. Explain why neither test layer replaces the other.

Debug a plausible mistake

Exercise

Repair a weakened caller contract

The API promises text-only titles. The negative caller must remain rejected, and the valid call must print Read. Keep the negative check inside the nonexecuted block; it is compile evidence, not a runtime request.

Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.

Find and fix the type errorTypeScript
function label(title: string | number): string {
  return String(title).trim();
}

console.log(label(" Read "));

if (false) {
  // @ts-expect-error Numeric titles are outside this API.
  label(25);
}

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

An unused expect-error directive reveals that the public type became too permissive.

Hint 2: a first step

Restore the intended parameter type instead of deleting the negative test.

Show one solution
TypeScript
function label(title: string): string {
  return String(title).trim();
}

console.log(label(" Read "));

if (false) {
  // @ts-expect-error Numeric titles are outside this API.
  label(25);
}
Text
Read

The runtime call worked before and after the repair; nothing at run time revealed the weakened API. The evidence was TS2578, "Unused '@ts-expect-error' directive": with string | number, label(25) became legal, so the directive had no error to expect. Narrowing the parameter back to string gives the directive its error again. The if (false) block keeps the negative call from ever running.

Your turn

Exercise

Compile-Time Contract Tests: practice

Create a readonly Book and a label function. Print Types for a valid call. Below it, add a function that is never called containing a deliberately missing-title call preceded by @ts-expect-error, as in the trace above. Click Check types: it should pass. Then weaken the function parameter so the title is optional, check again and read the unused-directive error. (In a real project the same negative test goes in a compile-only file; the optional local project on Day 7 shows one.)

Your workspaceTypeScript
// A valid call that runs, and a never-called function holding the negative test.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The negative test should fail if the public signature accidentally accepts an invalid call.

Hint 2: a first step

Put the directive on the line directly above label({}) inside a function you never call, and keep any other mistake off that line.

Show one solution
One possible solutionTypeScript
type Book = { readonly title: string };

function label(book: Book): string {
  return book.title;
}

function typeTests(): void {
  // @ts-expect-error A Book needs a title.
  label({});
}

console.log(label({ title: "Types" }));

Enable JavaScript to edit and type-check this example.

Text
Types

The directive sits directly above the one line that should be rejected, and that line breaks exactly one rule: the missing title. The check passes because {} is not a Book. Now weaken the parameter to book: { readonly title?: string }: label({}) becomes valid, and the checker reports Unused '@ts-expect-error' directive (TS2578). That failure is the test doing its job. The runtime call proves a valid book still works; only the never-called negative test proves an invalid one stays rejected. In a project, move it into a compile-only file such as label.type-test.ts that tsc --noEmit checks and nothing imports.

Change it and test it

Inspect the downloaded contracts.ts. Identify its four expected failures. Remove a readonly modifier temporarily and confirm checking fails because its expected error disappeared, then restore it. Never run dist/contracts.js: its invalid operations are not application examples.

Was this article helpful?

Your response is saved on this device.