expect-type
Compile-time tests for types. Useful to make sure types don't regress into being overly-permissive as changes go in over time.
Similar to Jest's expect
, but with type-awareness. Gives you access to a number of type-matchers that let you make assertions about the form of a reference or generic type parameter.
import {foo, bar} from '../foo'
import {expectTypeOf} from 'expect-type'
test('foo types', () => {
expectTypeOf(foo).toMatchTypeOf<{a: number}>()
expectTypeOf(bar).parameter(0).toBeString()
expectTypeOf(bar).returns.not.toBeAny()
})
It can be used in your existing test files - or any other type-checked file you'd like - it's built into existing tooling with no dependencies. No extra build step, cli tool, IDE extension, or lint plugin is needed. Just import the function and start writing tests. Failures will be at compile time - they'll appear in your IDE and when you run tsc
.
See below for lots more examples.
Contents
Installation and usage
npm install expect-type --save-dev
import {expectTypeOf} from 'expect-type'
Documentation
The expectTypeOf
method takes a single argument, or a generic parameter. Neither it, nor the functions chained off its return value, have any meaningful runtime behaviour. The assertions you write will be compile-time errors if they don't hold true.
Features
Check an object's type with .toEqualTypeOf
:
expectTypeOf({a: 1}).toEqualTypeOf<{a: number}>()
.toEqualTypeOf
can check that two concrete objects have equivalent types (note: when these assertions fail, the error messages can be less informative vs the generic typearg syntax above - see error messages docs):
expectTypeOf({a: 1}).toEqualTypeOf({a: 1})
.toEqualTypeOf
succeeds for objects with different values, but the same type:
expectTypeOf({a: 1}).toEqualTypeOf({a: 2})
.toEqualTypeOf
fails on extra properties:
expectTypeOf({a: 1, b: 1}).toEqualTypeOf<{a: number}>()
To allow for extra properties, use .toMatchTypeOf
. This is roughly equivalent to an extends
constraint in a function type argument.:
expectTypeOf({a: 1, b: 1}).toMatchTypeOf<{a: number}>()
.toEqualTypeOf
and .toMatchTypeOf
both fail on missing properties:
expectTypeOf({a: 1}).toEqualTypeOf<{a: number; b: number}>()
expectTypeOf({a: 1}).toMatchTypeOf<{a: number; b: number}>()
Another example of the difference between .toMatchTypeOf
and .toEqualTypeOf
, using generics. .toMatchTypeOf
can be used for "is-a" relationships:
type Fruit = {type: 'Fruit'; edible: boolean}
type Apple = {type: 'Fruit'; name: 'Apple'; edible: true}
expectTypeOf<Apple>().toMatchTypeOf<Fruit>()
expectTypeOf<Fruit>().toMatchTypeOf<Apple>()
expectTypeOf<Apple>().toEqualTypeOf<Fruit>()
Assertions can be inverted with .not
:
expectTypeOf({a: 1}).not.toMatchTypeOf({b: 1})
.not
can be easier than relying on // @ts-expect-error
:
type Fruit = {type: 'Fruit'; edible: boolean}
type Apple = {type: 'Fruit'; name: 'Apple'; edible: true}
expectTypeOf<Apple>().toMatchTypeOf<Fruit>()
expectTypeOf<Fruit>().not.toMatchTypeOf<Apple>()
expectTypeOf<Apple>().not.toEqualTypeOf<Fruit>()
Catch any/unknown/never types:
expectTypeOf<unknown>().toBeUnknown()
expectTypeOf<any>().toBeAny()
expectTypeOf<never>().toBeNever()
expectTypeOf<never>().toBeNumber()
.toEqualTypeOf
distinguishes between deeply-nested any
and unknown
properties:
expectTypeOf<{deeply: {nested: any}}>().not.toEqualTypeOf<{deeply: {nested: unknown}}>()
Test for basic javascript types:
expectTypeOf(() => 1).toBeFunction()
expectTypeOf({}).toBeObject()
expectTypeOf([]).toBeArray()
expectTypeOf('').toBeString()
expectTypeOf(1).toBeNumber()
expectTypeOf(true).toBeBoolean()
expectTypeOf(() => {}).returns.toBeVoid()
expectTypeOf(Promise.resolve(123)).resolves.toBeNumber()
expectTypeOf(Symbol(1)).toBeSymbol()
.toBe...
methods allow for types which extend the expected type:
expectTypeOf<number>().toBeNumber()
expectTypeOf<1>().toBeNumber()
expectTypeOf<any[]>().toBeArray()
expectTypeOf<number[]>().toBeArray()
expectTypeOf<string>().toBeString()
expectTypeOf<'foo'>().toBeString()
expectTypeOf<boolean>().toBeBoolean()
expectTypeOf<true>().toBeBoolean()
.toBe...
methods protect against any
:
const goodIntParser = (s: string) => Number.parseInt(s, 10)
const badIntParser = (s: string) => JSON.parse(s)
expectTypeOf(goodIntParser).returns.toBeNumber()
expectTypeOf(badIntParser).returns.toBeNumber()
Nullable types:
expectTypeOf(undefined).toBeUndefined()
expectTypeOf(undefined).toBeNullable()
expectTypeOf(undefined).not.toBeNull()
expectTypeOf(null).toBeNull()
expectTypeOf(null).toBeNullable()
expectTypeOf(null).not.toBeUndefined()
expectTypeOf<1 | undefined>().toBeNullable()
expectTypeOf<1 | null>().toBeNullable()
expectTypeOf<1 | undefined | null>().toBeNullable()
More .not
examples:
expectTypeOf(1).not.toBeUnknown()
expectTypeOf(1).not.toBeAny()
expectTypeOf(1).not.toBeNever()
expectTypeOf(1).not.toBeNull()
expectTypeOf(1).not.toBeUndefined()
expectTypeOf(1).not.toBeNullable()
Detect assignability of unioned types:
expectTypeOf<number>().toMatchTypeOf<string | number>()
expectTypeOf<string | number>().not.toMatchTypeOf<number>()
Use .extract
and .exclude
to narrow down complex union types:
type ResponsiveProp<T> = T | T[] | {xs?: T; sm?: T; md?: T}
const getResponsiveProp = <T>(_props: T): ResponsiveProp<T> => ({})
type CSSProperties = {margin?: string; padding?: string}
const cssProperties: CSSProperties = {margin: '1px', padding: '2px'}
expectTypeOf(getResponsiveProp(cssProperties))
.exclude<unknown[]>()
.exclude<{xs?: unknown}>()
.toEqualTypeOf<CSSProperties>()
expectTypeOf(getResponsiveProp(cssProperties))
.extract<unknown[]>()
.toEqualTypeOf<CSSProperties[]>()
expectTypeOf(getResponsiveProp(cssProperties))
.extract<{xs?: any}>()
.toEqualTypeOf<{xs?: CSSProperties; sm?: CSSProperties; md?: CSSProperties}>()
expectTypeOf<ResponsiveProp<number>>().exclude<number | number[]>().toHaveProperty('sm')
expectTypeOf<ResponsiveProp<number>>().exclude<number | number[]>().not.toHaveProperty('xxl')
.extract
and .exclude
return never if no types remain after exclusion:
type Person = {name: string; age: number}
type Customer = Person & {customerId: string}
type Employee = Person & {employeeId: string}
expectTypeOf<Customer | Employee>().extract<{foo: string}>().toBeNever()
expectTypeOf<Customer | Employee>().exclude<{name: string}>().toBeNever()
Make assertions about object properties:
const obj = {a: 1, b: ''}
expectTypeOf(obj).toHaveProperty('a')
expectTypeOf(obj).not.toHaveProperty('c')
expectTypeOf(obj).toHaveProperty('a').toBeNumber()
expectTypeOf(obj).toHaveProperty('b').toBeString()
expectTypeOf(obj).toHaveProperty('a').not.toBeString()
.toEqualTypeOf
can be used to distinguish between functions:
type NoParam = () => void
type HasParam = (s: string) => void
expectTypeOf<NoParam>().not.toEqualTypeOf<HasParam>()
But often it's preferable to use .parameters
or .returns
for more specific function assertions:
type NoParam = () => void
type HasParam = (s: string) => void
expectTypeOf<NoParam>().parameters.toEqualTypeOf<[]>()
expectTypeOf<NoParam>().returns.toBeVoid()
expectTypeOf<HasParam>().parameters.toEqualTypeOf<[string]>()
expectTypeOf<HasParam>().returns.toBeVoid()
More examples of ways to work with functions - parameters using .parameter(n)
or .parameters
, and return values using .returns
:
const f = (a: number) => [a, a]
expectTypeOf(f).toBeFunction()
expectTypeOf(f).toBeCallableWith(1)
expectTypeOf(f).not.toBeAny()
expectTypeOf(f).returns.not.toBeAny()
expectTypeOf(f).returns.toEqualTypeOf([1, 2])
expectTypeOf(f).returns.toEqualTypeOf([1, 2, 3])
expectTypeOf(f).parameter(0).not.toEqualTypeOf('1')
expectTypeOf(f).parameter(0).toEqualTypeOf(1)
expectTypeOf(1).parameter(0).toBeNever()
const twoArgFunc = (a: number, b: string) => ({a, b})
expectTypeOf(twoArgFunc).parameters.toEqualTypeOf<[number, string]>()
You can't use .toBeCallableWith
with .not
- you need to use ts-expect-error::
const f = (a: number) => [a, a]
expectTypeOf(f).toBeCallableWith('foo')
You can also check type guards & type assertions:
const assertNumber = (v: any): asserts v is number => {
if (typeof v !== 'number') {
throw new TypeError('Nope !')
}
}
expectTypeOf(assertNumber).asserts.toBeNumber()
const isString = (v: any): v is string => typeof v === 'string'
expectTypeOf(isString).guards.toBeString()
Assert on constructor parameters:
expectTypeOf(Date).toBeConstructibleWith('1970')
expectTypeOf(Date).toBeConstructibleWith(0)
expectTypeOf(Date).toBeConstructibleWith(new Date())
expectTypeOf(Date).toBeConstructibleWith()
expectTypeOf(Date).constructorParameters.toEqualTypeOf<[] | [string | number | Date]>()
Check function this
parameters:
function greet(this: {name: string}, message: string) {
return `Hello ${this.name}, here's your message: ${message}`
}
expectTypeOf(greet).thisParameter.toEqualTypeOf<{name: string}>()
Distinguish between functions with different this
parameters:
function greetFormal(this: {title: string; name: string}, message: string) {
return `Dear ${this.title} ${this.name}, here's your message: ${message}`
}
function greetCasual(this: {name: string}, message: string) {
return `Hi ${this.name}, here's your message: ${message}`
}
expectTypeOf(greetFormal).not.toEqualTypeOf(greetCasual)
Class instance types:
expectTypeOf(Date).instance.toHaveProperty('toISOString')
Promise resolution types can be checked with .resolves
:
const asyncFunc = async () => 123
expectTypeOf(asyncFunc).returns.resolves.toBeNumber()
Array items can be checked with .items
:
expectTypeOf([1, 2, 3]).items.toBeNumber()
expectTypeOf([1, 2, 3]).items.not.toBeString()
You can also compare arrays directly:
expectTypeOf<any[]>().not.toEqualTypeOf<number[]>()
Check that functions never return:
const thrower = () => {
throw new Error('oh no')
}
expectTypeOf(thrower).returns.toBeNever()
Generics can be used rather than references:
expectTypeOf<{a: string}>().not.toEqualTypeOf<{a: number}>()
Distinguish between missing/null/optional properties:
expectTypeOf<{a?: number}>().not.toEqualTypeOf<{}>()
expectTypeOf<{a?: number}>().not.toEqualTypeOf<{a: number}>()
expectTypeOf<{a?: number}>().not.toEqualTypeOf<{a: number | undefined}>()
expectTypeOf<{a?: number | null}>().not.toEqualTypeOf<{a: number | null}>()
expectTypeOf<{a: {b?: number}}>().not.toEqualTypeOf<{a: {}}>()
Detect the difference between regular and readonly properties:
type A1 = {readonly a: string; b: string}
type E1 = {a: string; b: string}
expectTypeOf<A1>().toMatchTypeOf<E1>()
expectTypeOf<A1>().not.toEqualTypeOf<E1>()
type A2 = {a: string; b: {readonly c: string}}
type E2 = {a: string; b: {c: string}}
expectTypeOf<A2>().toMatchTypeOf<E2>()
expectTypeOf<A2>().not.toEqualTypeOf<E2>()
Distinguish between classes with different constructors:
class A {
value: number
constructor(a: 1) {
this.value = a
}
}
class B {
value: number
constructor(b: 2) {
this.value = b
}
}
expectTypeOf<typeof A>().not.toEqualTypeOf<typeof B>()
class C {
value: number
constructor(c: 1) {
this.value = c
}
}
expectTypeOf<typeof A>().toEqualTypeOf<typeof C>()
Known limitation: Intersection types can cause issues with toEqualTypeOf
:
expectTypeOf<{a: 1} & {b: 2}>().toEqualTypeOf<{a: 1; b: 2}>()
To workaround for simple cases, you can use a mapped type:
type Simplify<T> = {[K in keyof T]: T[K]}
expectTypeOf<Simplify<{a: 1} & {b: 2}>>().toEqualTypeOf<{a: 1; b: 2}>()
But this won't work if the nesting is deeper in the type. For these situations, you can use the .branded
helper. Note that this comes at a performance cost, and can cause the compiler to 'give up' if used with excessively deep types, so use sparingly. This helper is under .branded
because it depply transforms the Actual and Expected types into a pseudo-AST:
expectTypeOf<{a: {b: 1} & {c: 1}}>().toEqualTypeOf<{a: {b: 1; c: 1}}>()
expectTypeOf<{a: {b: 1} & {c: 1}}>().branded.toEqualTypeOf<{a: {b: 1; c: 1}}>()
Be careful with .branded
for very deep or complex types, though. If possible you should find a way to simplify your test to avoid needing to use it:
expectTypeOf<() => () => () => () => 1>().branded.toEqualTypeOf<() => () => () => () => 2>()
expectTypeOf<() => () => () => () => 1>().toEqualTypeOf<() => () => () => () => 2>()
So, if you have an extremely deep type which ALSO has an intersection in it, you're out of luck and this library won't be able to test your type properly:
expectTypeOf<() => () => () => () => {a: 1} & {b: 2}>().toEqualTypeOf<
() => () => () => () => {a: 1; b: 2}
>()
expectTypeOf<() => () => () => () => {a: 1} & {b: 2}>().branded.toEqualTypeOf<
() => () => () => () => {a: 1; c: 2}
>()
Another limitation: passing this
references to expectTypeOf
results in errors.:
class B {
b = 'b'
foo() {
expectTypeOf(this).toEqualTypeOf(this)
expectTypeOf(this).toMatchTypeOf(this)
}
}
expectTypeOf(B).instance.toEqualTypeOf<{b: string; foo: () => void}>()
Where is .toExtend
?
A few people have asked for a method like toExtend
- this is essentially what toMatchTypeOf
is. There are some cases where it doesn't precisely match the extends
operator in TypeScript, but for most practical use cases, you can think of this as the same thing.
Internal type helpers
🚧 This library also exports some helper types for performing boolean operations on types, checking extension/equality in various ways, branding types, and checking for various special types like never
, any
, unknown
. Use at your own risk! Nothing is stopping you using these beyond this warning:
All internal types that are not documented here are not part of the supported API surface, and may be renamed, modified, or removed, without warning or documentation in release notes.
For a dedicated internal type library, feel free to look at the source code for inspiration - or better, use a library like type-fest.
Error messages
When types don't match, .toEqualTypeOf
and .toMatchTypeOf
use a special helper type to produce error messages that are as actionable as possible. But there's a bit of an nuance to understanding them. Since the assertions are written "fluently", the failure should be on the "expected" type, not the "actual" type (expect<Actual>().toEqualTypeOf<Expected>()
). This means that type errors can be a little confusing - so this library produces a MismatchInfo
type to try to make explicit what the expectation is. For example:
expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>()
Is an assertion that will fail, since {a: 1}
has type {a: number}
and not {a: string}
. The error message in this case will read something like this:
test/test.ts:999:999 - error TS2344: Type '{ a: string; }' does not satisfy the constraint '{ a: \\"Expected: string, Actual: number\\"; }'.
Types of property 'a' are incompatible.
Type 'string' is not assignable to type '\\"Expected: string, Actual: number\\"'.
999 expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>()
Note that the type constraint reported is a human-readable messaging specifying both the "expected" and "actual" types. Rather than taking the sentence Types of property 'a' are incompatible // Type 'string' is not assignable to type "Expected: string, Actual: number"
literally - just look at the property name ('a'
) and the message: Expected: string, Actual: number
. This will tell you what's wrong, in most cases. Extremely complex types will of course be more effort to debug, and may require some experimentation. Please raise an issue if the error messages are actually misleading.
The toBe...
methods (like toBeString
, toBeNumber
, toBeVoid
etc.) fail by resolving to a non-callable type when the Actual
type under test doesn't match up. For example, the failure for an assertion like expectTypeOf(1).toBeString()
will look something like this:
test/test.ts:999:999 - error TS2349: This expression is not callable.
Type 'ExpectString<number>' has no call signatures.
999 expectTypeOf(1).toBeString()
~~~~~~~~~~
The This expression is not callable
part isn't all that helpful - the meaningful error is the next line, Type 'ExpectString<number> has no call signatures
. This essentially means you passed a number but asserted it should be a string.
If TypeScript added support for "throw" types these error messagess could be improved. Until then they will take a certain amount of squinting.
Concrete "expected" objects vs typeargs
Error messages for an assertion like this:
expectTypeOf({a: 1}).toEqualTypeOf({a: ''})
Will be less helpful than for an assertion like this:
expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>()
This is because the TypeScript compiler needs to infer the typearg for the .toEqualTypeOf({a: ''})
style, and this library can only mark it as a failure by comparing it against a generic Mismatch
type. So, where possible, use a typearg rather than a concrete type for .toEqualTypeOf
and toMatchTypeOf
. If it's much more convenient to compare two concrete types, you can use typeof
:
const one = valueFromFunctionOne({some: {complex: inputs}})
const two = valueFromFunctionTwo({some: {other: inputs}})
expectTypeOf(one).toEqualTypeof<typeof two>()
Within test frameworks
Jest & eslint-plugin-jest
If you're using Jest along with eslint-plugin-jest
, you may get warnings from the jest/expect-expect
rule, complaining that "Test has no assertions" for tests that only use expectTypeOf()
.
To remove this warning, configure the ESlint rule to consider expectTypeOf
as an assertion:
"rules": {
"jest/expect-expect": [
"warn",
{
"assertFunctionNames": [
"expect", "expectTypeOf"
]
}
],
}
Similar projects
Other projects with similar goals:
tsd
is a CLI that runs the TypeScript type checker over assertionsts-expect
exports several generic helper types to perform type assertionsdtslint
does type checks via comment directives and tslinttype-plus
comes with various type and runtime TypeScript assertionsstatic-type-assert
type assertion functions
Comparison
The key differences in this project are:
- a fluent, jest-inspired API, making the difference between
actual
and expected
clear. This is helpful with complex types and assertions. - inverting assertions intuitively and easily via
expectTypeOf(...).not
- checks generics properly and strictly (tsd doesn't)
- first-class support for:
any
(as well as unknown
and never
) (see issues outstanding at time of writing in tsd for never and any).
- This can be especially useful in combination with
not
, to protect against functions returning too-permissive types. For example, const parseFile = (filename: string) => JSON.parse(readFileSync(filename).toString())
returns any
, which could lead to errors. After giving it a proper return-type, you can add a test for this with expect(parseFile).returns.not.toBeAny()
- object properties
- function parameters
- function return values
- constructor parameters
- class instances
- array item values
- nullable types
- assertions on types "matching" rather than exact type equality, for "is-a" relationships e.g.
expectTypeOf(square).toMatchTypeOf<Shape>()
- built into existing tooling. No extra build step, cli tool, IDE extension, or lint plugin is needed. Just import the function and start writing tests. Failures will be at compile time - they'll appear in your IDE and when you run
tsc
. - small implementation with no dependencies. Take a look! (tsd, for comparison, is 2.6MB because it ships a patched version of typescript).
Contributing
In most cases, it's worth checking existing issues or creating on to discuss a new feature or a bug fix before opening a pull request.
Once you're ready to make a pull request: clone the repo, and install pnpm if you don't have it already with npm install --global pnpm
. Lockfiles for npm
and yarn
are gitignored.
If you're adding a feature, you should write a self-contained usage example in the form of a test, in test/usage.test.ts. This file is used to populate the bulk of this readme using eslint-plugin-codegen, and to generate an "errors" test file, which captures the error messages that are emitted for failing assertions by the typescript compiler. So, the test name should be written as a human-readable sentence explaining the usage example. Have a look at the existing tests for an idea of the style.
After adding the tests, run npm run lint -- --fix
to update the readme, and npm test -- --updateSnapshot
to update the errors test. The generated documentation and tests should be pushed to the same branch as the source code, and submitted as a pull request. CI will test that the docs and tests are up to date if you forget to run these commands.