Menu

Testing TypeScript Code and Types

Lesson 2: Testing TypeScript Code and Types

What should you test?

Test type Checks Tool
Unit tests Functions return the right values Vitest, Jest, Node.js test runner
Type tests Types accept and reject the right inputs expectTypeOf, @ts-expect-error, tsc
Type check in CI The whole project compiles tsc --noEmit

Example: unit test with Vitest

// src/price.test.ts
import { describe, it, expect } from 'vitest';
import { applyCoupon } from './price.ts';

describe('applyCoupon', () => {
  it('applies 10% off for FRESH10', () => {
    expect(applyCoupon(95700, 'FRESH10')).toEqual({ ok: true, value: 86130 });
  });

  it('rejects unknown coupons', () => {
    expect(applyCoupon(95700, 'FAKE')).toEqual({ ok: false, error: 'Invalid coupon' });
  });
});

Example: type tests

// src/types.test-d.ts
import { expectTypeOf, test } from 'vitest';
import type { EventPayload } from './events.ts';
import { getProperty } from './utils.ts';

test('EventPayload picks the right member', () => {
  expectTypeOf<EventPayload<'order:placed'>>().toHaveProperty('total');
});

test('getProperty returns the property type', () => {
  const milk = { name: 'Milk 1L', price: 6400 };
  expectTypeOf(getProperty(milk, 'price')).toEqualTypeOf<number>();

  // @ts-expect-error – 'colour' is not a key of milk
  getProperty(milk, 'colour');
});
npx vitest run             # Unit tests
npx vitest --typecheck     # Type tests
npx tsc --noEmit           # Whole-project check

How it works

  • Vitest runs TypeScript test files directly.
  • expectTypeOf checks types at compile time; it has no effect at runtime.
  • @ts-expect-error fails the check if the line stops being an error, which proves your types reject bad input.
  • Type tests are most valuable for shared utility types and library APIs, where a mistake affects many files.

Common mistakes

Mistake Effect Fix
Running tests with a tool that strips types but never type-checking Type errors reach main Run tsc --noEmit in CI
Using as any in tests to build objects Tests pass with invalid data Create typed test factories
Writing type tests for simple app code Effort with little value Focus on reusable and complex types

Key takeaways

  • Unit tests check behaviour; type tests check your types; tsc --noEmit checks the whole project.
  • Use @ts-expect-error to prove invalid code is rejected.

Try it: Write Vitest tests for your cart total function, and a type test proving OrderStatus rejects 'lost'.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details