Gathering detailed insights and metrics for expect-type
Gathering detailed insights and metrics for expect-type
Gathering detailed insights and metrics for expect-type
Gathering detailed insights and metrics for expect-type
ts-expect
Checks TypeScript types match expected values
@types/expect
Stub TypeScript definitions entry for expect, which provides its own types definitions
eslint-plugin-expect-type
ESLint plugin with ^? Twoslash, $ExpectError, and $ExpectType type assertions. 🧩
expect-more
Curried JavaScript Type Testing Library with Zero Dependencies
Compile-time tests for types. Useful to make sure types don't regress into being overly-permissive as changes go in over time.
npm install expect-type
Typescript
Module System
Min. Node Version
Node Version
NPM Version
99.7
Supply Chain
100
Quality
80.7
Maintenance
100
Vulnerability
100
License
TypeScript (99.86%)
JavaScript (0.14%)
Total Downloads
27,477,046
Last Day
196,483
Last Week
1,181,603
Last Month
9,414,364
Last Year
21,178,914
435 Stars
126 Commits
8 Forks
5 Watching
16 Branches
6 Contributors
Minified
Minified + Gzipped
Latest Version
1.1.0
Package Id
expect-type@1.1.0
Unpacked Size
107.52 kB
Size
24.86 kB
File Count
13
NPM Version
10.8.2
Node Version
22.6.0
Publised On
09 Oct 2024
Cumulative downloads
Total Downloads
Last day
-9.3%
196,483
Compared to previous day
Last week
-44.3%
1,181,603
Compared to previous week
Last month
34.2%
9,414,364
Compared to previous month
Last year
360.9%
21,178,914
Compared to previous year
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 expect
, but with type-awareness. Gives you access to several type-matchers that let you make assertions about the form of a reference or generic type parameter.
1import {expectTypeOf} from 'expect-type' 2import {foo, bar} from '../foo' 3 4// make sure `foo` has type {a: number} 5expectTypeOf(foo).toMatchTypeOf<{a: number}>() 6 7// make sure `bar` is a function taking a string: 8expectTypeOf(bar).parameter(0).toBeString() 9expectTypeOf(bar).returns.not.toBeAny()
It can be used in your existing test files (and is actually built in to vitest). Or it can be used in 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.
1npm install expect-type --save-dev
1import {expectTypeOf} from 'expect-type'
The expectTypeOf
method takes a single argument or a generic type 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.
Check an object's type with .toEqualTypeOf
:
1expectTypeOf({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 type argument syntax above - see error messages docs):
1expectTypeOf({a: 1}).toEqualTypeOf({a: 1})
.toEqualTypeOf
succeeds for objects with different values, but the same type:
1expectTypeOf({a: 1}).toEqualTypeOf({a: 2})
.toEqualTypeOf
fails on excess properties:
1// @ts-expect-error 2expectTypeOf({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.:
1expectTypeOf({a: 1, b: 1}).toMatchTypeOf<{a: number}>()
.toEqualTypeOf
and .toMatchTypeOf
both fail on missing properties:
1// @ts-expect-error 2expectTypeOf({a: 1}).toEqualTypeOf<{a: number; b: number}>() 3// @ts-expect-error 4expectTypeOf({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:
1type Fruit = {type: 'Fruit'; edible: boolean} 2type Apple = {type: 'Fruit'; name: 'Apple'; edible: true} 3 4expectTypeOf<Apple>().toMatchTypeOf<Fruit>() 5 6// @ts-expect-error 7expectTypeOf<Fruit>().toMatchTypeOf<Apple>() 8 9// @ts-expect-error 10expectTypeOf<Apple>().toEqualTypeOf<Fruit>()
Assertions can be inverted with .not
:
1expectTypeOf({a: 1}).not.toMatchTypeOf({b: 1})
.not
can be easier than relying on // @ts-expect-error
:
1type Fruit = {type: 'Fruit'; edible: boolean} 2type Apple = {type: 'Fruit'; name: 'Apple'; edible: true} 3 4expectTypeOf<Apple>().toMatchTypeOf<Fruit>() 5 6expectTypeOf<Fruit>().not.toMatchTypeOf<Apple>() 7expectTypeOf<Apple>().not.toEqualTypeOf<Fruit>()
Catch any/unknown/never types:
1expectTypeOf<unknown>().toBeUnknown() 2expectTypeOf<any>().toBeAny() 3expectTypeOf<never>().toBeNever() 4 5// @ts-expect-error 6expectTypeOf<never>().toBeNumber()
.toEqualTypeOf
distinguishes between deeply-nested any
and unknown
properties:
1expectTypeOf<{deeply: {nested: any}}>().not.toEqualTypeOf<{deeply: {nested: unknown}}>()
You can test for basic JavaScript types:
1expectTypeOf(() => 1).toBeFunction() 2expectTypeOf({}).toBeObject() 3expectTypeOf([]).toBeArray() 4expectTypeOf('').toBeString() 5expectTypeOf(1).toBeNumber() 6expectTypeOf(true).toBeBoolean() 7expectTypeOf(() => {}).returns.toBeVoid() 8expectTypeOf(Promise.resolve(123)).resolves.toBeNumber() 9expectTypeOf(Symbol(1)).toBeSymbol() 10expectTypeOf(1n).toBeBigInt()
.toBe...
methods allow for types that extend the expected type:
1expectTypeOf<number>().toBeNumber() 2expectTypeOf<1>().toBeNumber() 3 4expectTypeOf<any[]>().toBeArray() 5expectTypeOf<number[]>().toBeArray() 6 7expectTypeOf<string>().toBeString() 8expectTypeOf<'foo'>().toBeString() 9 10expectTypeOf<boolean>().toBeBoolean() 11expectTypeOf<true>().toBeBoolean() 12 13expectTypeOf<bigint>().toBeBigInt() 14expectTypeOf<0n>().toBeBigInt()
.toBe...
methods protect against any
:
1const goodIntParser = (s: string) => Number.parseInt(s, 10) 2const badIntParser = (s: string) => JSON.parse(s) // uh-oh - works at runtime if the input is a number, but return 'any' 3 4expectTypeOf(goodIntParser).returns.toBeNumber() 5// @ts-expect-error - if you write a test like this, `.toBeNumber()` will let you know your implementation returns `any`. 6expectTypeOf(badIntParser).returns.toBeNumber()
Nullable types:
1expectTypeOf(undefined).toBeUndefined() 2expectTypeOf(undefined).toBeNullable() 3expectTypeOf(undefined).not.toBeNull() 4 5expectTypeOf(null).toBeNull() 6expectTypeOf(null).toBeNullable() 7expectTypeOf(null).not.toBeUndefined() 8 9expectTypeOf<1 | undefined>().toBeNullable() 10expectTypeOf<1 | null>().toBeNullable() 11expectTypeOf<1 | undefined | null>().toBeNullable()
More .not
examples:
1expectTypeOf(1).not.toBeUnknown() 2expectTypeOf(1).not.toBeAny() 3expectTypeOf(1).not.toBeNever() 4expectTypeOf(1).not.toBeNull() 5expectTypeOf(1).not.toBeUndefined() 6expectTypeOf(1).not.toBeNullable() 7expectTypeOf(1).not.toBeBigInt()
Detect assignability of unioned types:
1expectTypeOf<number>().toMatchTypeOf<string | number>() 2expectTypeOf<string | number>().not.toMatchTypeOf<number>()
Use .extract
and .exclude
to narrow down complex union types:
1type ResponsiveProp<T> = T | T[] | {xs?: T; sm?: T; md?: T} 2const getResponsiveProp = <T>(_props: T): ResponsiveProp<T> => ({}) 3type CSSProperties = {margin?: string; padding?: string} 4 5const cssProperties: CSSProperties = {margin: '1px', padding: '2px'} 6 7expectTypeOf(getResponsiveProp(cssProperties)) 8 .exclude<unknown[]>() 9 .exclude<{xs?: unknown}>() 10 .toEqualTypeOf<CSSProperties>() 11 12expectTypeOf(getResponsiveProp(cssProperties)) 13 .extract<unknown[]>() 14 .toEqualTypeOf<CSSProperties[]>() 15 16expectTypeOf(getResponsiveProp(cssProperties)) 17 .extract<{xs?: any}>() 18 .toEqualTypeOf<{xs?: CSSProperties; sm?: CSSProperties; md?: CSSProperties}>() 19 20expectTypeOf<ResponsiveProp<number>>().exclude<number | number[]>().toHaveProperty('sm') 21expectTypeOf<ResponsiveProp<number>>().exclude<number | number[]>().not.toHaveProperty('xxl')
.extract
and .exclude
return never if no types remain after exclusion:
1type Person = {name: string; age: number} 2type Customer = Person & {customerId: string} 3type Employee = Person & {employeeId: string} 4 5expectTypeOf<Customer | Employee>().extract<{foo: string}>().toBeNever() 6expectTypeOf<Customer | Employee>().exclude<{name: string}>().toBeNever()
Use .pick
to pick a set of properties from an object:
1type Person = {name: string; age: number} 2 3expectTypeOf<Person>().pick<'name'>().toEqualTypeOf<{name: string}>()
Use .omit
to remove a set of properties from an object:
1type Person = {name: string; age: number} 2 3expectTypeOf<Person>().omit<'name'>().toEqualTypeOf<{age: number}>()
Make assertions about object properties:
1const obj = {a: 1, b: ''} 2 3// check that properties exist (or don't) with `.toHaveProperty` 4expectTypeOf(obj).toHaveProperty('a') 5expectTypeOf(obj).not.toHaveProperty('c') 6 7// check types of properties 8expectTypeOf(obj).toHaveProperty('a').toBeNumber() 9expectTypeOf(obj).toHaveProperty('b').toBeString() 10expectTypeOf(obj).toHaveProperty('a').not.toBeString()
.toEqualTypeOf
can be used to distinguish between functions:
1type NoParam = () => void 2type HasParam = (s: string) => void 3 4expectTypeOf<NoParam>().not.toEqualTypeOf<HasParam>()
But often it's preferable to use .parameters
or .returns
for more specific function assertions:
1type NoParam = () => void 2type HasParam = (s: string) => void 3 4expectTypeOf<NoParam>().parameters.toEqualTypeOf<[]>() 5expectTypeOf<NoParam>().returns.toBeVoid() 6 7expectTypeOf<HasParam>().parameters.toEqualTypeOf<[string]>() 8expectTypeOf<HasParam>().returns.toBeVoid()
Up to ten overloads will produce union types for .parameters
and .returns
:
1type Factorize = { 2 (input: number): number[] 3 (input: bigint): bigint[] 4} 5 6expectTypeOf<Factorize>().parameters.not.toEqualTypeOf<[number]>() 7expectTypeOf<Factorize>().parameters.toEqualTypeOf<[number] | [bigint]>() 8expectTypeOf<Factorize>().returns.toEqualTypeOf<number[] | bigint[]>() 9 10expectTypeOf<Factorize>().parameter(0).toEqualTypeOf<number | bigint>()
Note that these aren't exactly like TypeScript's built-in Parameters<...> and ReturnType<...>:
The TypeScript builtins simply choose a single overload (see the Overloaded functions section for more information)
1type Factorize = { 2 (input: number): number[] 3 (input: bigint): bigint[] 4} 5 6// overload using `number` is ignored! 7expectTypeOf<Parameters<Factorize>>().toEqualTypeOf<[bigint]>() 8expectTypeOf<ReturnType<Factorize>>().toEqualTypeOf<bigint[]>()
More examples of ways to work with functions - parameters using .parameter(n)
or .parameters
, and return values using .returns
:
1const f = (a: number) => [a, a] 2 3expectTypeOf(f).toBeFunction() 4 5expectTypeOf(f).toBeCallableWith(1) 6expectTypeOf(f).not.toBeAny() 7expectTypeOf(f).returns.not.toBeAny() 8expectTypeOf(f).returns.toEqualTypeOf([1, 2]) 9expectTypeOf(f).returns.toEqualTypeOf([1, 2, 3]) 10expectTypeOf(f).parameter(0).not.toEqualTypeOf('1') 11expectTypeOf(f).parameter(0).toEqualTypeOf(1) 12expectTypeOf(1).parameter(0).toBeNever() 13 14const twoArgFunc = (a: number, b: string) => ({a, b}) 15 16expectTypeOf(twoArgFunc).parameters.toEqualTypeOf<[number, string]>()
.toBeCallableWith
allows for overloads. You can also use it to narrow down the return type for given input parameters.:
1type Factorize = { 2 (input: number): number[] 3 (input: bigint): bigint[] 4} 5 6expectTypeOf<Factorize>().toBeCallableWith(6) 7expectTypeOf<Factorize>().toBeCallableWith(6n)
.toBeCallableWith
returns a type that can be used to narrow down the return type for given input parameters.:
1type Factorize = { 2 (input: number): number[] 3 (input: bigint): bigint[] 4} 5expectTypeOf<Factorize>().toBeCallableWith(6).returns.toEqualTypeOf<number[]>() 6expectTypeOf<Factorize>().toBeCallableWith(6n).returns.toEqualTypeOf<bigint[]>()
.toBeCallableWith
can be used to narrow down the parameters of a function:
1type Delete = { 2 (path: string): void 3 (paths: string[], options?: {force: boolean}): void 4} 5 6expectTypeOf<Delete>().toBeCallableWith('abc').parameters.toEqualTypeOf<[string]>() 7expectTypeOf<Delete>() 8 .toBeCallableWith(['abc', 'def'], {force: true}) 9 .parameters.toEqualTypeOf<[string[], {force: boolean}?]>() 10 11expectTypeOf<Delete>().toBeCallableWith('abc').parameter(0).toBeString() 12expectTypeOf<Delete>().toBeCallableWith('abc').parameter(1).toBeUndefined() 13 14expectTypeOf<Delete>() 15 .toBeCallableWith(['abc', 'def', 'ghi']) 16 .parameter(0) 17 .toEqualTypeOf<string[]>() 18 19expectTypeOf<Delete>() 20 .toBeCallableWith(['abc', 'def', 'ghi']) 21 .parameter(1) 22 .toEqualTypeOf<{force: boolean} | undefined>()
You can't use .toBeCallableWith
with .not
- you need to use ts-expect-error::
1const f = (a: number) => [a, a] 2 3// @ts-expect-error 4expectTypeOf(f).toBeCallableWith('foo')
You can also check type guards & type assertions:
1const assertNumber = (v: any): asserts v is number => { 2 if (typeof v !== 'number') { 3 throw new TypeError('Nope !') 4 } 5} 6 7expectTypeOf(assertNumber).asserts.toBeNumber() 8 9const isString = (v: any): v is string => typeof v === 'string' 10 11expectTypeOf(isString).guards.toBeString() 12 13const isBigInt = (value: any): value is bigint => typeof value === 'bigint' 14 15expectTypeOf(isBigInt).guards.toBeBigInt()
Assert on constructor parameters:
1expectTypeOf(Date).toBeConstructibleWith('1970') 2expectTypeOf(Date).toBeConstructibleWith(0) 3expectTypeOf(Date).toBeConstructibleWith(new Date()) 4expectTypeOf(Date).toBeConstructibleWith() 5 6expectTypeOf(Date).constructorParameters.toEqualTypeOf< 7 | [] 8 | [value: string | number] 9 | [value: string | number | Date] 10 | [ 11 year: number, 12 monthIndex: number, 13 date?: number | undefined, 14 hours?: number | undefined, 15 minutes?: number | undefined, 16 seconds?: number | undefined, 17 ms?: number | undefined, 18 ] 19>()
Constructor overloads:
1class DBConnection { 2 constructor() 3 constructor(connectionString: string) 4 constructor(options: {host: string; port: number}) 5 constructor(..._: unknown[]) {} 6} 7 8expectTypeOf(DBConnection).toBeConstructibleWith() 9expectTypeOf(DBConnection).toBeConstructibleWith('localhost') 10expectTypeOf(DBConnection).toBeConstructibleWith({host: 'localhost', port: 1234}) 11// @ts-expect-error - as when calling `new DBConnection(...)` you can't actually use the `(...args: unknown[])` overlaod, it's purely for the implementation. 12expectTypeOf(DBConnection).toBeConstructibleWith(1, 2)
Check function this
parameters:
1function greet(this: {name: string}, message: string) { 2 return `Hello ${this.name}, here's your message: ${message}` 3} 4 5expectTypeOf(greet).thisParameter.toEqualTypeOf<{name: string}>()
Distinguish between functions with different this
parameters:
1function greetFormal(this: {title: string; name: string}, message: string) { 2 return `Dear ${this.title} ${this.name}, here's your message: ${message}` 3} 4 5function greetCasual(this: {name: string}, message: string) { 6 return `Hi ${this.name}, here's your message: ${message}` 7} 8 9expectTypeOf(greetFormal).not.toEqualTypeOf(greetCasual)
Class instance types:
1expectTypeOf(Date).instance.toHaveProperty('toISOString')
Promise resolution types can be checked with .resolves
:
1const asyncFunc = async () => 123 2 3expectTypeOf(asyncFunc).returns.resolves.toBeNumber()
Array items can be checked with .items
:
1expectTypeOf([1, 2, 3]).items.toBeNumber() 2expectTypeOf([1, 2, 3]).items.not.toBeString()
You can also compare arrays directly:
1expectTypeOf<any[]>().not.toEqualTypeOf<number[]>()
Check that functions never return:
1const thrower = () => { 2 throw new Error('oh no') 3} 4 5expectTypeOf(thrower).returns.toBeNever()
Generics can be used rather than references:
1expectTypeOf<{a: string}>().not.toEqualTypeOf<{a: number}>()
Distinguish between missing/null/optional properties:
1expectTypeOf<{a?: number}>().not.toEqualTypeOf<{}>() 2expectTypeOf<{a?: number}>().not.toEqualTypeOf<{a: number}>() 3expectTypeOf<{a?: number}>().not.toEqualTypeOf<{a: number | undefined}>() 4expectTypeOf<{a?: number | null}>().not.toEqualTypeOf<{a: number | null}>() 5expectTypeOf<{a: {b?: number}}>().not.toEqualTypeOf<{a: {}}>()
Detect the difference between regular and readonly
properties:
1type A1 = {readonly a: string; b: string} 2type E1 = {a: string; b: string} 3 4expectTypeOf<A1>().toMatchTypeOf<E1>() 5expectTypeOf<A1>().not.toEqualTypeOf<E1>() 6 7type A2 = {a: string; b: {readonly c: string}} 8type E2 = {a: string; b: {c: string}} 9 10expectTypeOf<A2>().toMatchTypeOf<E2>() 11expectTypeOf<A2>().not.toEqualTypeOf<E2>()
Distinguish between classes with different constructors:
1class A { 2 value: number 3 constructor(a: 1) { 4 this.value = a 5 } 6} 7class B { 8 value: number 9 constructor(b: 2) { 10 this.value = b 11 } 12} 13 14expectTypeOf<typeof A>().not.toEqualTypeOf<typeof B>() 15 16class C { 17 value: number 18 constructor(c: 1) { 19 this.value = c 20 } 21} 22 23expectTypeOf<typeof A>().toEqualTypeOf<typeof C>()
Known limitation: Intersection types can cause issues with toEqualTypeOf
:
1// @ts-expect-error the following line doesn't compile, even though the types are arguably the same. 2// See https://github.com/mmkal/expect-type/pull/21 3expectTypeOf<{a: 1} & {b: 2}>().toEqualTypeOf<{a: 1; b: 2}>()
To workaround for simple cases, you can use a mapped type:
1type Simplify<T> = {[K in keyof T]: T[K]} 2 3expectTypeOf<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 deeply transforms the Actual and Expected types into a pseudo-AST:
1// @ts-expect-error 2expectTypeOf<{a: {b: 1} & {c: 1}}>().toEqualTypeOf<{a: {b: 1; c: 1}}>() 3 4expectTypeOf<{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:
1// This *should* result in an error, but the "branding" mechanism produces too large a type and TypeScript just gives up! https://github.com/microsoft/TypeScript/issues/50670 2expectTypeOf<() => () => () => () => 1>().branded.toEqualTypeOf<() => () => () => () => 2>() 3 4// @ts-expect-error the non-branded implementation catches the error as expected. 5expectTypeOf<() => () => () => () => 1>().toEqualTypeOf<() => () => () => () => 2>()
So, if you have an extremely deep type that ALSO has an intersection in it, you're out of luck and this library won't be able to test your type properly:
1// @ts-expect-error this fails, but it should succeed. 2expectTypeOf<() => () => () => () => {a: 1} & {b: 2}>().toEqualTypeOf< 3 () => () => () => () => {a: 1; b: 2} 4>() 5 6// this succeeds, but it should fail. 7expectTypeOf<() => () => () => () => {a: 1} & {b: 2}>().branded.toEqualTypeOf< 8 () => () => () => () => {a: 1; c: 2} 9>()
Another limitation: passing this
references to expectTypeOf
results in errors.:
1class B { 2 b = 'b' 3 4 foo() { 5 // @ts-expect-error 6 expectTypeOf(this).toEqualTypeOf(this) 7 // @ts-expect-error 8 expectTypeOf(this).toMatchTypeOf(this) 9 } 10} 11 12// Instead of the above, try something like this: 13expectTypeOf(B).instance.toEqualTypeOf<{b: string; foo: () => void}>()
Overloads limitation for TypeScript <5.3: Due to a TypeScript bug fixed in 5.3, overloaded functions which include an overload resembling (...args: unknown[]) => unknown
will exclude unknown[]
from .parameters
and exclude unknown
from .returns
:
1type Factorize = { 2 (...args: unknown[]): unknown 3 (input: number): number[] 4 (input: bigint): bigint[] 5} 6 7expectTypeOf<Factorize>().parameters.toEqualTypeOf<[number] | [bigint]>() 8expectTypeOf<Factorize>().returns.toEqualTypeOf<number[] | bigint[]>()
This overload, however, allows any input and returns an unknown output anyway, so it's not very useful. If you are worried about this for some reason, you'll have to update TypeScript to 5.3+.
For complex types, an assertion might fail when it should if the Actual
type contains a deeply-nested intersection type but the Expected
doesn't. In these cases you can use .branded
as described above:
1// @ts-expect-error this unfortunately fails - a TypeScript limitation prevents making this pass without a big perf hit 2expectTypeOf<{a: {b: 1} & {c: 1}}>().toEqualTypeOf<{a: {b: 1; c: 1}}>() 3 4expectTypeOf<{a: {b: 1} & {c: 1}}>().branded.toEqualTypeOf<{a: {b: 1; c: 1}}>()
.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.
🚧 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 from 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.
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 a 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:
1expectTypeOf({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 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 messages could be improved. Until then they will take a certain amount of squinting.
Error messages for an assertion like this:
1expectTypeOf({a: 1}).toEqualTypeOf({a: ''})
Will be less helpful than for an assertion like this:
1expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>()
This is because the TypeScript compiler needs to infer the type argument 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 type argument rather than a concrete type for .toEqualTypeOf
and toMatchTypeOf
. If it's much more convenient to compare two concrete types, you can use typeof
:
1const one = valueFromFunctionOne({some: {complex: inputs}})
2const two = valueFromFunctionTwo({some: {other: inputs}})
3
4expectTypeOf(one).toEqualTypeof<typeof two>()
Due to a TypeScript design limitation, the native TypeScript Parameters<...>
and ReturnType<...>
helpers only return types from one variant of an overloaded function. This limitation doesn't apply to expect-type, since it is not used to author TypeScript code, only to assert on existing types. So, we use a workaround for this TypeScript behaviour to assert on all overloads as a union (actually, not necessarily all - we cap out at 10 overloads).
expectTypeOf
is built in to vitest, so you can import expectTypeOf
from the vitest library directly if you prefer. Note that there is no set release cadence, at time of writing, so vitest may not always be using the very latest version.
1import {expectTypeOf} from 'vitest' 2import {mount} from './mount.js' 3 4test('my types work properly', () => { 5 expectTypeOf(mount).toBeFunction() 6 expectTypeOf(mount).parameter(0).toMatchTypeOf<{name: string}>() 7 8 expectTypeOf(mount({name: 42})).toBeString() 9})
eslint-plugin-jest
If you're using Jest along with eslint-plugin-jest
, and you put assertions inside test(...)
definitions, 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:
1"rules": { 2 // ... 3 "jest/expect-expect": [ 4 "warn", 5 { 6 "assertFunctionNames": [ 7 "expect", "expectTypeOf" 8 ] 9 } 10 ], 11 // ... 12}
A summary of some of the limitations of this library. Some of these are documented more fully elsewhere.
.brand
in these cases - and accept the performance hit that it comes with.toBeCallableWith
will likely fail if you try to use it with a generic function or an overload. See this issue for an example and how to work around it..parameter
and .parameters
helpers. This matches how the built-in TypeScript helper Parameters<...>
works. This may be improved in the future though (see related issue).expectTypeOf(this).toEqualTypeOf(this)
inside class methods does not work.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 functionsThe key differences in this project are:
actual
and expected
clear. This is helpful with complex types and assertions.expectTypeOf(...).not
any
(as well as unknown
and never
) (see issues outstanding at time of writing in tsd for never and any).
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()
expectTypeOf(square).toMatchTypeOf<Shape>()
tsc
.There is a CI job called test-types
that checks whether the tests still pass with certain older TypeScript versions. To check the supported TypeScript versions, refer to the job definition.
In most cases, it's worth checking existing issues or creating one 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.
Limitations of the library are documented through tests in usage.test.ts
. This means that if a future TypeScript version (or library version) fixes the limitation, the test will start failing, and it will be automatically removed from the documentation once it no longer applies.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
branch protection is not maximal on development and all release branches
Details
Reason
dependency not pinned by hash detected -- score normalized to 5
Details
Reason
Found 7/22 approved changesets -- score normalized to 3
Reason
8 existing vulnerabilities detected
Details
Reason
0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-01-06
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More