TypeScript · Lesson 94 of 120
Testing with Types
Expect errors.
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.

- 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.
| key | value |
|---|---|
| Runner | Vitest or node:test |
| Type tests | @ts-expect-error |
| CI | tsc --noEmit |
| Both | behaviour 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