Typroof
TypeScript type testing with a fast CLI tool and a smooth WYSIWYG editor experience.
https://github.com/user-attachments/assets/53aa8f97-c580-428e-89b2-2d07d1c5680d
Installation
npm install --save-dev typroof
Quickstart
Define your types
Assume that you write a string-utils.ts file with the following type definitions:
export type Append<S extends string, Ext extends string> = `${S}${Ext}`;
export type Prepend<S extends string, Start extends string> = `${Start}${S}`;
export const append = <S extends string, Ext extends string>(s: S, ext: Ext): Append<S, Ext> =>
`${s}${ext}`;
Add a type test
Create a string-utils.proof.ts file in the same directory to test them:
import { describe, equal, error, expect, extend, it, test } from 'typroof';
import { append } from './string-utils';
import type { Append, Prepend } from './string-utils';
test('Append', () => {
expect<Append<'foo', 'bar'>>().to(equal<'foo'>);
expect<Append<'foo', 'bar'>>().to(extend<string>);
expect<Append<'foo', 'bar'>>().not.to(extend<number>);
expect(append('foo', 'bar')).to(equal('foobar' as const));
});
Oops! Seems we have made a mistake, and TypeScript language server is already showing you the error message in your editor:
expect<Append<'foo', 'bar'>>().to(equal<'foo'>);
// ~~~~~~~~~~~~
// Argument of type '...' is not assignable to parameter
// of type '"Expect `'foobar'` to equal `'foo'`, but does not"'
This is the WYSIWYG editor experience Typroof provides—instant feedback right in your editor.
Let’s ignore this error for now and see what happens when we run the tests.
Run the CLI
Run typroof to test your type definitions:
npx typroof
You’ll see the error clearly reported:
❯ src/string-utils.proof.ts (1)
× Append
❯ src/string-utils.proof.ts:6:37
Expect Append<'foo', 'bar'> to equal "foo", but got "foobar".
Test Files 1 failed (1)
Tests 1 failed (1)
Start at 17:50:11
Duration 2ms
Let’s fix the error in the test file:
- expect<Append<'foo', 'bar'>>().to(equal<'foo'>);
+ expect<Append<'foo', 'bar'>>().to(equal<'foobar'>);
Success! You’ve written and verified your first type test with Typroof. 🎉
✓ src/string-utils.proof.ts (1)
✓ Append
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 17:51:26
Duration 2ms
[!NOTE]
By default, Typroof does not perform type checking on test files. This allows matchers like .to(error) to work properly without requiring manual @ts-expect-error comments. If you want to enable type checking on your test files, you can use the --check option when running Typroof:
npx typroof --check
Usage
After getting started with Typroof, let’s explore its core concepts and patterns in more depth.
API Overview
Typroof provides a familiar testing API that resembles Jest:
test/it: Create individual test cases
describe: Group related tests together
expect: Create an assertion on a type or value
.to(matcher): Apply a matcher to validate the assertion
.not.to(matcher): Negate a matcher expectation
Assertion Patterns
Typroof offers flexible ways to write assertions:
// Testing a type directly (most common for type utilities)
expect<MyType<Input>>().to(equal<Expected>);
// Testing a value’s type (useful for functions)
expect(myFunction('input')).to(equal<ExpectedReturnType>);
// Negating an assertion
expect<MyType>().not.to(beAny);
// Testing for errors
// @ts-expect-error
expect<InvalidType>().to(error);
Matcher Flexibility
Matchers can receive expected types in two ways:
// As a type parameter (preferred for testing generic types)
expect<MyType<'input'>>().to(equal<'expected'>);
// As a value parameter (useful for function return types)
const result = computeSomething();
const expected = computeSomethingElse();
expect(result).to(equal(expected));
Composing Tests
describe('StringUtils', () => {
describe('Append', () => {
it('concatenates two strings', () => {
expect<Append<'hello', ' world'>>().to(equal<'hello world'>);
});
it('returns a string type', () => {
expect<Append<'a', 'b'>>().to(extend<string>);
});
});
describe('Split', () => {
it('splits a string into tuple', () => {
expect<Split<'a-b-c', '-'>>().to(equal<['a', 'b', 'c']>);
});
});
});
Testing For Type Errors
Test that invalid types correctly produce errors:
describe('NumericUtilities', () => {
it('rejects non-numeric inputs', () => {
// @ts-expect-error - string is not assignable to number
expect<Add<'not-a-number', 5>>().to(error);
});
});
Running Tests
Run tests with the Typroof CLI:
npx typroof [optional path]
By default, Typroof will find all .proof.ts files or files in proof/ directories and analyze them. To customize which files to test, you can create a typroof.config.ts file in the root directory of your project. See Configuration for more information.
Matchers
Matchers are the core of Typroof’s assertion system. They let you validate type relationships and characteristics in your tests.
Matcher Basics
Each matcher can be used with the expect().to() or expect().not.to() syntax:
// Basic matcher usage
expect<MyType>().to(matcherName<OptionalTypeArg>);
// Negated matcher usage
expect<MyType>().not.to(matcherName<OptionalTypeArg>);
Built-in Matchers
Typroof provides two categories of matchers for different testing needs:
Equality and Basic Type Matchers
| Matcher |
Description |
Example |
equal<T> |
Checks for exact type equality |
expect<'hello'>().to(equal<'hello'>) |
error |
Verifies a type produces a compilation error |
expect<ConcatString<'foo', 42>>().to(error) |
beAny |
Checks if a type is any |
expect<any>().to(beAny) |
beNever |
Checks if a type is never |
expect<never>().to(beNever) |
beNull |
Checks if a type is null |
expect<null>().to(beNull) |
beUndefined |
Checks if a type is undefined |
expect<undefined>().to(beUndefined) |
beNullish |
Checks if a type is null, undefined or their union |
expect().to(beNullish) |
beTrue/beFalse |
Checks if a type is true/false |
expect<true>().to(beTrue) |
matchBoolean |
Checks if a type is true, false or boolean |
expect<boolean>().to(matchBoolean) |
Type Relationship Matchers
| Matcher |
Description |
Example |
extend<T> |
Checks if a type is assignable to another |
expect<'hello'>().to(extend<string>) |
strictExtend<T> |
Like extend but stricter with any/never |
expect<string>().to(strictExtend<string>) |
cover<T> |
Checks if a type is a supertype of another |
expect<string>().to(cover<'hello'>) |
strictCover<T> |
Like cover but stricter with any/never |
expect<string>().to(strictCover<'hello'>) |
Matcher Examples
Testing type utilities:
// Testing a string template utility
type Prefix<T extends string, P extends string> = `${P}${T}`;
test('Prefix type', () => {
expect<Prefix<'World', 'Hello '>>().to(equal<'Hello World'>);
expect<Prefix<'file', 'index.'>>().to(extend<string>);
expect<Prefix<'foo', 'bar'>>().not.to(equal<'foobar'>);
});
Testing for compilation errors:
// Testing constraint violations
test('NumericId constraints', () => {
type NumericId<T extends number> = T;
expect<NumericId<42>>().to(extend<number>);
// @ts-expect-error - String not assignable to number
expect<NumericId<'42'>>().to(error);
});
Understanding Special Types
TypeScript’s any and never types have special behavior in type relationships:
any is both a subtype and supertype of all types.
never is a subtype of all types but has no subtypes.
This can lead to unexpected results in type tests:
// Regular extend allows any to be assigned to anything
expect<any>().to(extend<string>); // passes
// strictExtend prevents this
expect<any>().not.to(strictExtend<string>); // passes
For more predictable behavior with these types, use strictExtend and strictCover when testing type relationships involving any or never.
Configuration
Typroof can be customized through a configuration file to control which files are tested and how tests are run.
Configuration File
Create a typroof.config.ts file in your project root:
import { defineConfig } from 'typroof/config';
export default defineConfig({
testFiles: '**/*.types.test.ts',
});
You can use either .ts, .mts, .cts, .js, .mjs or .cjs as the extension of the config file. The priority is .ts > .mts > .cts > .js > .mjs > .cjs.
Available Options
| Option |
Type |
Default |
Description |
tsConfigFilePath |
string |
'./tsconfig.json' |
Path to the TypeScript configuration file |
testFiles |
string | string[] |
['**/*.proof.{ts,tsx}', 'proof/**/*.{ts,tsx}'] |
Glob pattern(s) for test files |
check |
boolean |
false |
Enable type checking on test files |
checkFiles |
string | string[] |
Same as testFiles |
Glob pattern(s) for files to check. This option is only used when check is true |
compilerOptions |
ts.CompilerOptions |
{} |
Additional TypeScript compiler options to override those in tsconfig.json |
plugins |
Plugin[] |
[] |
Typroof plugins that extend functionality |
Import Notice
When creating your configuration file, import from the specific subpath:
// ✅ Correct import
import { defineConfig } from 'typroof/config';
CLI Usage
You can run Typroof from the command line:
# Run in current directory
npx typroof
# Run in specific directory
npx typroof /path/to/project
# Specify test files
npx typroof --files "src/**/*.proof.ts"
# Use custom config file
npx typroof --config ./typroof.config.ts
# Use custom tsconfig.json and enable type checking
npx typroof --check --project ./tsconfig.test.json
# Get help
npx typroof --help
Available options:
--files, -f: Glob pattern(s) for test files.
--config, -c: Path to config file.
--project, -p: Path to tsconfig.json file.
--check: Enable type checking on test files.
--check-files: Glob pattern(s) for files to check. This option is only used when --check is enabled.
--help: Show help information.
--version: Show version information.
Programmatic Usage
You can use Typroof programmatically within your own Node.js scripts or tools:
import typroof, { formatGroupResult, formatSummary } from 'typroof';
// Run Typroof with default options
const startedAt = new Date();
const results = await typroof();
const finishedAt = new Date();
// Display results
for (const result of results) {
console.log(formatGroupResult(result.rootGroupResult));
console.log();
}
// Print summary
console.log(
formatSummary({ groups: results.map((r) => r.rootGroupResult), startedAt, finishedAt }),
);
API Options
The typroof() function accepts the same options available in the configuration file, plus an additional cwd option:
// Run with custom options
const results = await typroof({
// Standard config options
testFiles: ['src/**/*.proof.ts'],
compilerOptions: { strictNullChecks: true },
plugins: [],
// Additional API-only option
cwd: '/path/to/project', // Custom working directory
});
The cwd option sets the base directory for:
- Finding the default
tsconfig.json file (${cwd}/tsconfig.json).
- Resolving relative paths in your configuration.
If not provided, cwd defaults to process.cwd().
Plugin API & How It Works
Typroof supports plugins to extend its functionality with custom matchers. The plugin system allows you to:
- Create custom type matchers.
- Share matchers as reusable packages.
- Extend Typroof’s core functionality.