Course contentsShow
← TypeScript
Lesson 1149 of 1,79627. Declaration FilesFree lesson

Testing Declaration Files

Use tsd or dtslint to test that your .d.ts files correctly describe the expected types and catch errors.

Testing Declaration Files

What you'll learn: How to use specialized tools like tsd or dtslint to verify that your .d.ts files provide the correct types and catch type errors.

Why Testing Declaration Files Matters

You've learned how to write declaration files to describe JavaScript libraries, but how do you know they're correct? Unlike regular TypeScript code, .d.ts files don't get executed — they only describe types. A subtle mistake in a declaration file won't cause a runtime error, but it will give developers the wrong autocomplete suggestions or allow type-unsafe code to compile.

Think of it like writing a user manual for a product. You need to verify that your manual accurately describes how the product works, not just that the manual itself is grammatically correct. Testing declaration files ensures your type descriptions match reality.

The Testing Challenge

Traditional unit tests verify runtime behavior, but declaration files have no runtime. You need to test type-level behavior: does this type accept the right values? Does it reject the wrong ones? Does it infer the correct result?

Tools for Declaration Testing

tsd

tsd is a modern tool specifically designed to test TypeScript type definitions using special assertion functions:

  • expectType<T>() — asserts a value has exactly type T
  • expectError() — asserts code produces a compile-time error
  • expectNotType<T>() — asserts a value does NOT have type T
  • expectAssignable<T>() — asserts a value is assignable to type T

dtslint

dtslint was the original tool created by the DefinitelyTyped team. It uses special comment annotations to test types, but has largely been superseded by tsd for new projects.

How Testing Works

You write test files that look like code but are actually assertions about types. The testing tool runs the TypeScript compiler and verifies that the type system behaves as expected — catching both false positives (code that should error but doesn't) and false negatives (code that errors but shouldn't).

Why This Matters

When you publish types for a library, users depend on those types being accurate. A type that's too permissive allows bugs; a type that's too restrictive blocks valid usage. Testing your declarations ensures they correctly represent the actual API contract.

Key Takeaway: Use tsd or dtslint to write type-level tests that verify your declaration files correctly describe expected types and reject invalid ones — ensuring your .d.ts files are reliable documentation.