TypeScript theorytheory 0/50 · 0%
Testing · medium

35. Testing typed code

Writing assertions that verify both behaviour and types.

Unit tests for TypeScript run against the compiled JavaScript, so a testing framework like Vitest or Jest exercises runtime behaviour exactly as JS would, while `tsc`/the editor catches type errors separately, before tests even run.

ts
function calculateFee(amountWei: bigint, bps: number): bigint {
  return (amountWei * BigInt(bps)) / 10000n;
}

// example test (Vitest-style)
import { describe, it, expect } from "vitest";

describe("calculateFee", () => {
  it("charges the right basis points", () => {
    expect(calculateFee(1_000_000n, 50)).toBe(5000n);
  });
});

Good tests for typed code focus on behaviour and edge cases (zero amounts, negative inputs, boundary values) rather than re-testing what the compiler already guarantees (like argument types). Type-level testing tools (`expectTypeOf`, `tsd`) exist for library authors who want to assert that generic inference produces the expected type.

Check your understanding

  1. 1. Do TypeScript's type checks replace the need for runtime tests?

  2. 2. What should typed-code unit tests mainly focus on?

  3. 3. What do type-testing tools like `tsd` or `expectTypeOf` check?