Skip to content

Public Type Tests

The Course
•
20 min study

A type test asks whether a caller is accepted or rejected, not whether the runtime implements a rule. Include positive usage so a contract that rejects everything cannot pass by accident. Negative usage needs a targeted diagnostic, not a broad ignore comment.

@ts-expect-error requires the next line to contain a diagnostic. If the public type becomes too permissive, the directive becomes unused and checking fails. It does not verify a particular error code: keep each invalid usage minimal so another unrelated error cannot hide the intended regression.

In the download, consumer.ts imports through the package's public export and its built .d.ts files. It checks valid branded ids and payloads, plus invalid raw ids, missing title, wrong callback fields, async listeners, readonly assignment and an unknown channel. It is never a runtime entry point.

The browser error lab below shows one misuse without suppression so you can inspect the actual compiler message. The local negative tests then assert that this kind of misuse remains rejected during future edits.

Predict, check, and run

Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.

Predict, then runTypeScript
type Listener<T> = (value: T) => undefined;

const listener: Listener<{ title: string }> = book => {
  console.log(book.title);
};

listener({ title: "Types" });

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types

Read the compiler error

Predict the rejected relationship before checking. Read the real diagnostic and its source location; fix the contract or the value instead of hiding it with an assertion.

Find and fix the type errorTypeScript
type Listener<T> = (value: T) => undefined;

const callback: Listener<number> = async value => {
  console.log(value);
};

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The second line is the key one: Type 'Promise<void>' is not assignable to type 'undefined'. The failure is in the return type of the listener, not its parameter.

The Promise return is unsupported. A compile-only negative test can protect that rejection without running the callback.

Keep each negative caller focused

An expected-error directive confirms that some diagnostic exists on the following line. It does not confirm which diagnostic. A wrong payload with both a missing brand and a missing title could keep failing for the brand after the title contract was accidentally weakened.

Establish every unrelated precondition first, then violate one relationship. Include valid calls through the actual public export too. This combination prevents both false confidence from unrelated errors and an unusably strict API that rejects everyone.

Keep each negative caller focused: traceTypeScript
type Item = {
  title: string;

  pages: number;
};

function label(item: Item): string {
  return item.title;
}

function negative(): void {
  // @ts-expect-error only the required title is missing
  label({ pages: 120 });
}

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

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types

The negative line keeps pages valid. Weakening the title requirement can now make this specific directive unused instead of leaving another unrelated error in its place.

Keep each negative caller focused: contrastTypeScript
type Listener<T> = (value: T) => undefined;

function negative(): void {
  // @ts-expect-error the return policy rejects Promise-returning listeners
  const listener: Listener<number> = async value => {};
}

const sync: Listener<number> = value => {};

console.log(sync(0) === undefined);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
true

The valid callback checks usability; the negative callback checks the async restriction. Widening undefined to void should break the negative test rather than change a runtime fixture.

Pin a derived type exactly

@ts-expect-error and ordinary assignments test assignability: whether one value is accepted. That is too weak for the derived types of Days 1 and 2. If EventName accidentally widens to string, assigning "added" to it still compiles, so a positive test passes while the type has lost all its precision.

An exact-equality helper closes that gap. Equal<A, B> is true only when A and B are the same type; Expect accepts only true, so a false comparison becomes a compiler error. The odd-looking comparison of two generic functions is the standard trick for this: it treats any, optional properties and readonly modifiers strictly, which a pair of extends checks does not. Copy it as a utility; libraries such as expect-type and Vitest's expectTypeOf provide the same check.

Find and fix the type error: a widened derived typeTypeScript
type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
    ? true
    : false;
type Expect<T extends true> = T;

type Events = { added: { title: string }; removed: { id: string } };
type EventName = keyof Events | string;

const name: EventName = "added";

type NameTest = Expect<Equal<EventName, "added" | "removed">>;

console.log(name);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The key line is TS2344: Type 'false' does not satisfy the constraint 'true'. It is reported on the Expect line, and it says only that the two types differ; read the two arguments to find out how. keyof Events | string simplifies to plain string, which is not "added" | "removed". Meanwhile the assignment const name: EventName = "added" was accepted without complaint. Remove | string and the test passes.

Use exact tests for derived types and focused @ts-expect-error lines for rejected callers. Together they pin both what a type is and what it refuses.

Try the rule on new inputs

Inspect each real consumer directive and name the one relationship it violates. Then weaken that relationship and require an unused-directive failure. Restore declarations by rebuilding from source.

Trace the contract before building

Treat a declaration as a public interface that needs regression examples. Positive cases protect useful inference and accepted calls. Negative cases protect meaningful rejections. A test that merely imports a type can pass while the relationships consumers depend on have already been widened away.

Change one public signature temporarily and predict which test should fail. Inspect the diagnostic so a negative case cannot pass for an unrelated syntax error. Keep each fixture small enough to explain without running it. Then restore the signature and run the runtime suite too: these type tests do not prove listener identity, dispatch order, validation, or cleanup behavior.

Build it yourself

Exercise

Public Type Tests: practice

Write type tests for the derived event types below. Pin exactly that EventOf<"added">["payload"] is { title: string }, and that AnyEvent is exactly the union of the two event objects written out by hand. Add one focused negative test showing that EventOf<"renamed"> is rejected. Then build a removed event and print its type and type tests checked.

Your workspaceTypeScript
type Events = { added: { title: string }; removed: { id: string } };
type EventOf<K extends keyof Events> = { type: K; payload: Events[K] };
type AnyEvent = { [K in keyof Events]: EventOf<K> }[keyof Events];

// Add Equal and Expect, the exact tests, and one negative test.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The derived types are what consumers rely on, so state the expected types by hand and compare them exactly. A rejected type argument is a caller error, which belongs in a never-called function with @ts-expect-error.

Hint 2: a first step

Copy Equal and Expect from the lesson. Several Expect lines can sit in one tuple type, type Tests = [Expect<...>, Expect<...>], so they share a name.

Show one solution
One possible solutionTypeScript
type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
    ? true
    : false;
type Expect<T extends true> = T;

type Events = { added: { title: string }; removed: { id: string } };
type EventOf<K extends keyof Events> = { type: K; payload: Events[K] };
type AnyEvent = { [K in keyof Events]: EventOf<K> }[keyof Events];

type Tests = [
  Expect<Equal<EventOf<"added">["payload"], { title: string }>>,
  Expect<
    Equal<
      AnyEvent,
      | { type: "added"; payload: { title: string } }
      | { type: "removed"; payload: { id: string } }
    >
  >
];

function negativeContracts(): void {
  // @ts-expect-error renamed is not an event name
  const renamed: EventOf<"renamed"> = { type: "renamed", payload: {} };
}

const event: AnyEvent = { type: "removed", payload: { id: "b1" } };

console.log(event.type);
console.log("type tests checked");

Enable JavaScript to edit and type-check this example.

Text
removed
type tests checked

The tests show their value under mutation. Change AnyEvent to EventOf<keyof Events> and the runtime line still compiles, because { type: "removed", payload: { id: "b1" } } is assignable to the weaker type. The second Expect fails with TS2344, though: the mutated type allows type: "added" with a removed payload, and the exact test notices. The negative test protects the opposite direction: if EventOf stopped constraining K, its directive would become unused.

Change it and test it

Make the mutation from the solution and read the Expect error. Then remove the @ts-expect-error comment and read the real error it was expecting. Restore the clean version before continuing.

Was this article helpful?

Your response is saved on this device.