AI Hints
Home›TypeScript Tutorial›Testing, Migrating, Mistakes
TypeScript · Lesson 94 of 120

Testing with Types

Expect errors.

⏱ 2 min read▶ Video at 1:13:26🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Tests check behaviour while running. Types can be tested too. A special comment says the next line should be a type error. If it isn't, the compiler complains.

Testing with Types
From the video: Testing with Types
  • Test behaviour
  • Test types too
  • Expect errors

Two kinds of tests

Node's assert checks the behaviour, delivery is free from fifty pounds. The ts expect error comment proves a string total is rejected. Run it. Both kinds of tests pass.

app.tstypescript
import assert from "node:assert/strict";

function deliveryCost(total: number): number {
  return total >= 50 ? 0 : 4.99;
}

assert.equal(deliveryCost(50), 0);
assert.equal(deliveryCost(49.99), 4.99);

// @ts-expect-error: totals must be numbers
deliveryCost("65");

console.log("All tests passed");
Output
All tests passed

In real projects

Use a test runner, like Vitest, or Node's own test runner. Keep type tests next to the code they check. And run the type checker in your CI pipeline, along with the tests.

keyvalue
RunnerVitest or node:test
Type tests@ts-expect-error
CItsc --noEmit
Bothbehaviour and types

Summary

Test behaviour with assertions, and types with ts expect error. Next, migrating JavaScript.

Key takeaways
  • assert
  • @ts-expect-error
  • tsc in CI
Next up: Migrating JavaScript — step by step