Testing Type Definitions
Testing Type Definitions — why it matters
Type-level tests check what TypeScript accepts or rejects, not what JavaScript prints. A well-typed library should compile valid usage and reject invalid usage. Dedicated tooling or compiler fixtures can verify inferred types, exported declarations, and expected error diagnostics.
What you’ll learn
- Explain testing type definitions and the problem it solves.
- Identify the relevant compile-time checks and runtime responsibilities.
- Run the example, predict its output, and try a realistic modification.
Understand the mechanism
TestString resolves to true, satisfying the Assert constraint. Changing the tested input to number causes a compile-time type error before JavaScript executes.
A passing runtime unit test cannot prove that the compiler inferred the intended generic signature for users of a library.
Follow the concept flow
Run the primary TypeScript example
Save as testing-type-definitions.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.
TypeScript source
type IsString<T> = T extends string ? true : false;
type Assert<T extends true> = T;
type TestString = Assert<IsString<string>>;
const checked: TestString = true;
console.log(checked);Verified output
trueCompile: npx tsc --strict --target es2022 --module commonjs testing-type-definitions.ts; run: node testing-type-definitions.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.
The example demonstrates the code-level behavior; the related configuration or test commands are shown separately when needed.
Trace the result
TestString resolves to true, satisfying the Assert constraint. Changing the tested input to number causes a compile-time type error before JavaScript executes.
Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.
Common mistake and correction
A passing runtime unit test cannot prove that the compiler inferred the intended generic signature for users of a library.
Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.
Practice the concept
Write an Assert test that verifies ReturnType of a function is number; change it to string and observe the error.
Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.
Check your understanding
What to remember
Type-level tests check what TypeScript accepts or rejects, not what JavaScript prints.
Run the primary example, then complete the practice task or environment-specific lab.
Reaching the recap and completing the quizzes are separate milestones.