Testing TypeScript Generic Types and Utility Types

Testing TypeScript Generic Types and Utility Types

TypeScript generics and utility types need testing too — but they exist at the type level, not just at runtime. This post covers how to test both the compile-time behavior (types flow correctly) and runtime behavior (the code does what it should) of generic code.

Key Takeaways

Generic functions have two contracts to verify. The runtime contract (correct output for given input) and the type contract (correct output type for given input type). Both need testing.

@ts-expect-error is a test assertion. It asserts that a line of code should not type-check. If the error disappears, the assertion fails — protecting you from accidentally relaxing type constraints.

Conditional types need explicit instantiation to test. TypeScript won't always resolve conditional types unless you give it concrete type arguments — use explicit type variables in your test cases.

expect-type tests type relationships, not values. It's the compile-time equivalent of expect(x).toBe(y) — but for types. Use it alongside runtime assertions, not instead of them.

Distribution over union types is a common source of bugs. Test your generic types with union inputs explicitly — T = string | null often behaves differently than you expect.

Generic types are the hardest part of TypeScript to test well. They exist at the type level, which means most testing tools — Jest, Vitest, Playwright — can't see them. But they have real contracts that can be broken, and those breakages cause real bugs. This post covers a complete strategy for testing generic functions and utility types at both the type and runtime levels.

The Two Contracts of Generic Code

Every generic function has two contracts:

  1. The runtime contract: given input values, produce the correct output values.
  2. The type contract: given input types, infer the correct output types.

A function can satisfy one while violating the other:

// Satisfies the runtime contract, violates the type contract
function identity<T>(x: T): any {  // return type is 'any', not 'T'
  return x;
}

// All runtime tests pass:
expect(identity(42)).toBe(42);       // ✓
expect(identity('hi')).toBe('hi');   // ✓

// But the type contract is broken:
const result = identity(42);
// TypeScript thinks result is 'any', not 'number'
// This code compiles but shouldn't:
result.nonExistentMethod();

Testing only at runtime misses the type contract violation. You need both layers.

Testing Runtime Behavior of Generics

Runtime tests for generic functions work like any other Jest test — instantiate the generic with concrete types and assert on the output:

function zip<A, B>(a: A[], b: B[]): [A, B][] {
  const len = Math.min(a.length, b.length);
  return Array.from({ length: len }, (_, i) => [a[i], b[i]]);
}

describe('zip', () => {
  it('pairs elements from two arrays', () => {
    const result = zip([1, 2, 3], ['a', 'b', 'c']);
    expect(result).toEqual([[1, 'a'], [2, 'b'], [3, 'c']]);
  });

  it('truncates to the shorter array', () => {
    const result = zip([1, 2, 3], ['a', 'b']);
    expect(result).toHaveLength(2);
  });

  it('handles empty arrays', () => {
    expect(zip([], [1, 2, 3])).toEqual([]);
    expect(zip([1, 2, 3], [])).toEqual([]);
  });

  it('works with same types', () => {
    const result = zip([1, 2], [3, 4]);
    expect(result).toEqual([[1, 3], [2, 4]]);
  });
});

The key is to test with multiple different type instantiations — don't just test zip<number, string> and call it done. Test same types, different types, edge cases.

Compile-Time Type Assertions with expect-type

Install expect-type:

npm install --save-dev expect-type

Then add type assertions alongside your runtime tests:

import { expectType, expectAssignable, expectNotType } from 'expect-type';
import { zip } from '../zip';

describe('zip type contracts', () => {
  it('infers tuple type from input arrays', () => {
    const result = zip([1, 2], ['a', 'b']);
    expectType<[number, string][]>(result);
  });

  it('handles readonly arrays', () => {
    const a = [1, 2, 3] as const;
    const b = ['x', 'y', 'z'] as const;
    const result = zip(a, b);
    // Result is still mutable tuples, not readonly
    expectAssignable<[1 | 2 | 3, 'x' | 'y' | 'z'][]>(result);
  });

  it('does not widen to any', () => {
    const result = zip([1], ['a']);
    expectNotType<any>(result);
    expectNotType<any[]>(result);
  });
});

These assertions happen at compile time. If zip accidentally returns any[], the expectNotType<any[]> check makes the file fail to compile — you never even get to run the tests.

Testing with @ts-expect-error

@ts-expect-error is a TypeScript directive that asserts the next line should produce a type error. If the error doesn't occur, TypeScript itself errors on the @ts-expect-error comment:

function divide<T extends number>(a: T, b: Exclude<T, 0>): number {
  return a / b;
}

// These should work:
divide(10, 5);    // ✓
divide(3.14, 2);  // ✓

// These should NOT compile (type constraint violations):
// @ts-expect-error — 0 is excluded from the second parameter
divide(10, 0);

// @ts-expect-error — string is not assignable to number
divide('10', 5);

This pattern is particularly powerful for testing that your constraints actually prevent misuse. If someone later relaxes the constraint (e.g., removes Exclude<T, 0>), the @ts-expect-error becomes an error — you get notified automatically.

Testing Conditional Types

Conditional types require compile-time testing because they don't exist at runtime:

type IsArray<T> = T extends any[] ? true : false;
type Flatten<T> = T extends Array<infer Item> ? Item : T;

Test them with expectType:

import { expectType } from 'expect-type';

// IsArray tests
expectType<true>({} as IsArray<string[]>);
expectType<true>({} as IsArray<number[]>);
expectType<false>({} as IsArray<string>);
expectType<false>({} as IsArray<{ length: number }>); // array-like, but not an array

// Flatten tests
expectType<string>({} as Flatten<string[]>);
expectType<number>({} as Flatten<number[]>);
expectType<string>({} as Flatten<string>);  // non-array returns T unchanged
expectType<{ id: number }>({} as Flatten<{ id: number }[]>);

The {} as Type pattern is the standard way to create a value of a type for compile-time assertion purposes without providing a real value.

Distribution Over Unions — A Common Bug Source

Conditional types distribute over union types by default. This is a common source of bugs and confusion:

type NonNullable<T> = T extends null | undefined ? never : T;

// With a non-union type:
type A = NonNullable<string>;  // string

// With a union type — distribution happens:
type B = NonNullable<string | null | undefined>;
// Expands to: (string extends null | undefined ? never : string) | (null extends ...) | (undefined extends ...)
// = string | never | never = string

Test distribution explicitly:

expectType<string>({} as NonNullable<string | null>);
expectType<string | number>({} as NonNullable<string | number | null | undefined>);
expectType<never>({} as NonNullable<null | undefined>);

When you want to prevent distribution, wrap in a tuple:

type IsUnion<T> = [T] extends [T]  // This prevents distribution
  ? T extends T
    ? Exclude<T, T> extends never
      ? false
      : true
    : never
  : never;

Test both the distributed and non-distributed behavior to verify your intent is implemented correctly.

Testing Utility Types

TypeScript's built-in utility types (Partial, Required, Readonly, Pick, Omit, etc.) are well-tested by Microsoft, but your custom utility types need the same rigor:

// A custom utility type
type DeepPartial<T> = T extends object
  ? { [P in keyof T]?: DeepPartial<T[P]> }
  : T;

interface UserProfile {
  id: string;
  name: string;
  address: {
    street: string;
    city: string;
    country: string;
  };
  preferences: {
    theme: 'light' | 'dark';
    notifications: boolean;
  };
}

type PartialUserProfile = DeepPartial<UserProfile>;

Test it:

describe('DeepPartial type', () => {
  it('makes top-level properties optional', () => {
    // Should compile — all fields optional
    const profile: PartialUserProfile = {};
    const withName: PartialUserProfile = { name: 'Alice' };
    expectType<string | undefined>(({} as PartialUserProfile).name);
  });

  it('makes nested properties optional', () => {
    // Should compile — nested fields also optional
    const withPartialAddress: PartialUserProfile = {
      address: { city: 'London' },  // only city, no street or country
    };
    expectType<string | undefined>(({} as PartialUserProfile).address?.city);
  });

  it('preserves primitive types', () => {
    // Primitives should not become object types
    expectType<string | undefined>(({} as PartialUserProfile).id);
    expectAssignable<'light' | 'dark' | undefined>(
      ({} as PartialUserProfile).preferences?.theme
    );
  });
});

Testing Generic Constraints

When a generic has a constraint (T extends SomeType), test that the constraint actually works:

function mergeObjects<T extends object, U extends object>(a: T, b: U): T & U {
  return { ...a, ...b };
}

// Runtime tests
describe('mergeObjects', () => {
  it('merges two objects', () => {
    const result = mergeObjects({ a: 1 }, { b: 2 });
    expect(result).toEqual({ a: 1, b: 2 });
  });

  it('later properties override earlier ones', () => {
    const result = mergeObjects({ x: 1 }, { x: 2 });
    expect(result.x).toBe(2);
  });
});

// Type constraint tests
describe('mergeObjects type constraints', () => {
  it('returns intersection type', () => {
    const result = mergeObjects({ a: 1 }, { b: 'two' });
    expectType<{ a: number } & { b: string }>(result);

    // Can access both properties with correct types
    expectType<number>(result.a);
    expectType<string>(result.b);
  });

  it('rejects primitives', () => {
    // @ts-expect-error — number is not assignable to object
    mergeObjects(1, { b: 2 });

    // @ts-expect-error — string is not assignable to object
    mergeObjects({ a: 1 }, 'hello');
  });
});

Testing Mapped Types

Mapped types transform the shape of an object type — test that the transformation is correct:

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

interface Point {
  x: number;
  y: number;
}

type PointGetters = Getters<Point>;
// Should be: { getX: () => number; getY: () => number; }
// Test the mapped type shape
type TestPointGetters = {
  getX: () => number;
  getY: () => number;
};

// These assertions verify the mapping is correct
expectType<TestPointGetters>({} as PointGetters);

// Individual property types
expectType<() => number>({} as PointGetters['getX']);
expectType<() => number>({} as PointGetters['getY']);

// The original keys should not exist on the mapped type
// @ts-expect-error — 'x' is not a key of PointGetters
const x: PointGetters['x'] = null;

Organizing Type Tests

Type tests work best in dedicated files alongside your implementation:

src/
├── utils/
│   ├── types.ts           # utility types
│   ├── types.test.ts      # runtime tests for any runtime behavior
│   └── types.type-test.ts # compile-time type tests only

Some teams exclude .type-test.ts files from Jest runs entirely (using testPathIgnorePatterns) since they never have runtime assertions — they're only meaningful to tsc:

// jest.config.ts
testPathIgnorePatterns: [
  '/node_modules/',
  '\\.type-test\\.ts$',
],

Then run type tests as part of your TypeScript compilation check:

npx tsc --noEmit  # catches all type-test.ts failures along with real type errors

Testing with tsd for Library Authors

If you're publishing a TypeScript library, tsd is purpose-built for testing the types your library exports:

npm install --save-dev tsd
// index.test-d.ts
import { expectType, expectError } from 'tsd';
import { myLibraryFunction } from '.';

expectType<string>(myLibraryFunction('input'));
expectError(myLibraryFunction(123));  // number not accepted
// package.json
{
  "scripts": {
    "test:types": "tsd"
  }
}

tsd is stricter than expect-type in some ways and integrates with npm test pipelines cleanly — worth considering if your package's exported types are a core part of its API.

Testing generic types is one of the less glamorous parts of TypeScript development, but it pays dividends. When you refactor a utility type and the type tests immediately tell you what broke, you realize why the discipline matters. Your generics have contracts — make TypeScript enforce them.

Read more

Start now free