ts-spec
v1.8.0
Published
A small library for testing your types
Readme
ts-spec
A small library for testing your types.
Features:
- Prevent false negatives and silent regressions;
- Organise you tests and declutter your namespace.
- Compare types and values with the same API;
How to install
npm install --save-dev ts-specHow to use
Write your tests:
import { test } from 'ts-spec';
test('test description', t =>
t.equal ([1, 2, 3]) <string[]>()
);See them fail in your IDE:


Or run them with tsc:
tests/your-test-file.ts:4:5 - error TS2322:
Type 'FailingTest<"test description", number[], string[]>'
is not assignable to type 'PassingTest'
t.equal ([1, 2, 3], <string[]>_)
~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error.Limitation
The only way to expect a type error is with the directive @ts-expect-error.
Test descriptions must appear on the same line as the directive for them to show up in the report:
// @ts-expect-error: `foo` does not accept strings
{ const test = foo('bar') }tests/your-test-file.ts:3:1 - error TS2578: Unused '@ts-expect-error' directive.
// @ts-expect-error: `foo` does not accept strings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Note that they won't appear in VS Code's Problems view
The downside of expecting errors is that they can have other reasons to occur than the one stated in the description. For example, it could be that foo actually accepts strings but is not in scope.
Documentation
Writing tests | Assertions | Equality
Writing tests
test | check
The function test (also aliased as check) is composed of a test description and a callback.
The callback can return one or multiple assertions, which can be wrapped in arbitrary ways in tuples, promises, functions or nested tests, enabling all kinds of patterns and test hierarchies.
Single assertion
test('test description', t =>
t.pass()
);Array of assertions
Implicitly returning a tuple of assertions conveniently reports failures where they occur:
test('test description', t => [
t.pass(),
t.fail()
// ~~~~~~~ pretty convenient
]);Explicit returns enable sharing local variables, but they report failures at the callback level and print noisier error messages, unless you force type checking to happen sooner:
test('test description', t => {
const foo = 42;
return t.force([
// ---------
t.pass(),
t.fail()
// ~~~~~~~ still good
])
});Assertion returning functions
This pattern can be useful for testing type narrowing with only little boilerplate:
test('`isArray` type guard narrows its input', t =>
(input: number[] | number) =>
Array.isArray(input)
&& t.equal(input)<number[]>()
);It also makes unresolved generics accessible for testing:
test('`Filter` returns useful type when input is generic', t =>
<T extends (number | string)[]>() =>
t.equal<Filter<T, number>, number[]>()
)And of course it allows to scope variables:
test('`bar` returns true', t => [
() => {
const foo = 42;
return t.true(bar(foo))
},
() => {
const foo = 2001;
return t.true(bar(foo))
}
]);Nested tests
Tests can be nested in order to reduce repetition in test titles:
test('Given Foo', t =>
// titles are accumulated by wrapping the current title with the parent `t`
test(t('When Bar'), t =>
// -------------
test(t('Then A'), t => t.fail()),
// ----------- ~~~~~~~~
// 'FailingTest<"Given Foo ❱ When Bar ❱ Then A", never, true>'
// is not assignable to type 'PassingTest'
)
)Nested tests are also a good option for sharing local variables because failures are reported by test leaves and don't bubble up:
test('Given `foo` is 42', t => {
const foo = 42;
return [
test(t('Something is true'), t =>
t.true(bar(foo))
),
test(t('Something else'), t =>
t.fail()
// ~~~~~~~ still good
)
]
});group
Like test, group enables accumulating context but it does not enable writing assertions and its callback should be void.
Groups eliminate some boilerplate and keep the indentation level under control:
group('Given `foo` is 42', g => {
const foo = 42;
test(g('Something is true'), t =>
t.true(bar(foo))
)
test(g('Something else'), t =>
t.fail()
// ~~~~~~~~
)
});.as
.as enables to wrap a describe block or a test from your runtime testing framework of choice and have access to the ts-spec context in place of the runtime context. This gives flexibility in how you structure unit tests.
Here we are doing a runtime test and a type-level check separately:
import { expect, describe, test } from 'vitest';
import { group, check } from 'ts-spec';
group.as(describe)('given a user service', g => {
const service = { createUser: (name: string) => ({ id: 1, name }) };
// runtime test
test('creates user correctly', () => {
expect(service.createUser('Alice')).toEqual({ id: 1, name: 'Alice' });
});
// type-level test, ignored by vitest
check(g('user has correct type'), t =>
t.equal(service.createUser('Alice'))<{ id: number, name: string }>(),
)
});This is useful in vitest when setting requireAssertions to true, as vitest expectTypeOf in a vitest test would would yield an error.
Here we are mixing runtime and type-level checks in the same test, without having to mix and match ts-spec assertions with vitest expectTypeOf, which would be inconsistent:
group.as(describe)('given a user service', g => {
const service = { createUser: (name: string) => ({ id: 1, name }) };
check.as(test)(g('creates user correctly'), t => {
const user = service.createUser('Alice');
expect(user).toEqual({ id: 1, name: 'Alice' });
return t.equal(user)<{ id: number, name: string }>();
});
});Note that the accumulated title can also be passed as a second argument to .as, for convenience:
group.as(describe)('given a user service', g => {
check.as(test, g)('creates user correctly', t => {
[...]
});
});test.with | check.with
Instruments test.as | check.as context methods to yield a runtime assertion when used, enabling the use of type-level checks which count as passing tests in the test report, with requireAssertions enabled.
import { expect, describe, test } from 'vitest';
import { group, check } from 'ts-spec';
check.with(() => expect(true).toBe(true));
group.as(describe)('given a user service', g => {
const service = { createUser: (name: string) => ({ id: 1, name }) };
check.as(test, g)('user has correct type', t => {
// will NOT produce the error `expected any number of assertion, but got none`
return t.equal(service.createUser('Alice'))<{ id: number, name: string }>();
});
});Assertions
The library supports the following assertions
t.assertion()t.not.assertion()They are made available as an argument in test's callback.

They can be called in different ways depending on whether you test values (a) or types (A)
and whether you prefer the placeholder or the curried syntax:
import { _ } from 'ts-spec't.equal<A, B>()t.equal(a, b)
t.equal(a, <B>_)
t.equal(<A>_, b)
t.equal(<A>_, <B>_)t.equal (a) (b)
t.equal (a) <B>()
t.equal <A>() (b)
t.equal <A>() <B>()Custom assertions
You can leverage currying to create your own assertions:
test('Bar and Baz are Foo', t => {
const isFoo = t.equal<Foo>();
return [
isFoo<Bar>(),
isFoo<Baz>()
];
})If you want to share a custom assertion across tests, you must bring Context into scope and connect it like so:
import { Context } from 'ts-spec';
const isFoo = <D>(t: Context<D>) => t.equal<Foo>();Then, on the call site, apply the assertion with the context object before use:
test('Bar is Foo', t =>
isFoo(t)<Bar>()
)Equality
Tests can fail for 2 reasons:
- The condition of the assertion did not hold;
any,neverorunknownaccidentally appeared in your type.
A process of disambiguation converts any, never and unknown to unique symbols. The resulting behaviour is what you would expect from strict equality:
test('`any` is equal to itself', t =>
t.equal<{ foo: Set<any> }, { foo: Set<any> }>()
)
test('`any` is not equal to `number`', t =>
t.equal<{ foo: Set<any> }, { foo: Set<number> }>()
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FailingTest
)
Asymmetric equality
Assertions are set up with the assumption that the type under test should always be the narrowest of the two operands, the other one is thus not disambiguated in order to enable loose tests to be written:
test('It is possible to extend `any`', t => [
t.extends<number[], any[]>()
t.includes<any[], number[]>()
])
test('But the reverse is likely a mistake', t => [
t.extends<any[], number[]>()
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FailingTest
t.includes<number[], any[]>()
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FailingTest
])You can refer to the assertions table for a synthetic view of the differences between assertions.
Placeholders
If you want the type under test to include any, never or unknown in an asymmetric assertion, you can import the placeholders _any, _never and _unknown:
import { _never } from 'ts-spec'
test('use `_never` to extend `never`', t => [
t.extends<[1, 2, never], [number, number, _never]>(),
])User classes
Disambiguation works out of the box for arbitrarily nested built-in types. However, user classes need to be registered for them to be disambiguated:
import { test } from 'ts-spec'
import { Type, A } from 'free-types'
// The class we want to test
class Foo<T extends number> {
constructor(private value: T) { ... }
}
// A free type constructor for that class
interface $Foo extends Type<[number]> { type: Foo<A<this>> }
// which we register into ts-spec.TypesMap
declare module 'ts-spec' {
interface TypesMap { Foo: $Foo }
}
// Now we are safe
test('Registered user classes are disambiguated', t =>
t.equal<Foo<any>, Foo<number>>()
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FailingTest
)The
TypesMaprepository is shared with thefree-typeslibrary, which meansdeclare module 'free-types'would also work.
See the free-types documentation for more information about free type constructors.
