chore(deps): update dependency expect-type to v1 #6654
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR contains the following updates:
^0.20.0
->^1.1.0
Release Notes
mmkal/expect-type (expect-type)
v1.1.0
Compare Source
What's Changed
.toBeBigInt()
by @aryaemami59 in https://github.com/mmkal/expect-type/pull/123Full Changelog: mmkal/expect-type@v1.0.0...v1.1.0
v1.0.0
Compare Source
v1! 🎉🎉🎉
After many years being commitment-phobic, expect-type is now in v1.
This release does not add any user facing features on top of v0.20.0 or v1.0.0-rc.0. It's just "making it official". For anyone new to the project, or coming here from vitest or viteconf (👋 ), the usage docs from the readme are pasted below.
For anyone on an old-ish v0 version, here are links to the non-trivial changes that have gone in since v0.15.0:
.pick
and.omit
thanks to @aryaemami59.branded
helper for the old behaviour. Also support functionthis
parameters - thank to @trevorade and @papbFull usage docs below, for newbies (head to the readme to keep up to date):
docs from readme
Installation and usage
Documentation
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.Features
Check an object's type with
.toEqualTypeOf
:.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):.toEqualTypeOf
succeeds for objects with different values, but the same type:.toEqualTypeOf
fails on excess properties:To allow for extra properties, use
.toMatchTypeOf
. This is roughly equivalent to anextends
constraint in a function type argument.:.toEqualTypeOf
and.toMatchTypeOf
both fail on missing properties:Another example of the difference between
.toMatchTypeOf
and.toEqualTypeOf
, using generics..toMatchTypeOf
can be used for "is-a" relationships:Assertions can be inverted with
.not
:.not
can be easier than relying on// @​ts-expect-error
:Catch any/unknown/never types:
.toEqualTypeOf
distinguishes between deeply-nestedany
andunknown
properties:You can test for basic JavaScript types:
.toBe...
methods allow for types that extend the expected type:.toBe...
methods protect againstany
:Nullable types:
More
.not
examples:Detect assignability of unioned types:
Use
.extract
and.exclude
to narrow down complex union types:.extract
and.exclude
return never if no types remain after exclusion:Use
.pick
to pick a set of properties from an object:Use
.omit
to remove a set of properties from an object:Make assertions about object properties:
.toEqualTypeOf
can be used to distinguish between functions:But often it's preferable to use
.parameters
or.returns
for more specific function assertions:Up to ten overloads will produce union types for
.parameters
and.returns
: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)
More examples of ways to work with functions - parameters using
.parameter(n)
or.parameters
, and return values using.returns
:.toBeCallableWith
allows for overloads. You can also use it to narrow down the return type for given input parameters.:.toBeCallableWith
returns a type that can be used to narrow down the return type for given input parameters.:.toBeCallableWith
can be used to narrow down the parameters of a function:You can't use
.toBeCallableWith
with.not
- you need to use ts-expect-error::You can also check type guards & type assertions:
Assert on constructor parameters:
Constructor overloads:
Check function
this
parameters:Distinguish between functions with different
this
parameters:Class instance types:
Promise resolution types can be checked with
.resolves
:Array items can be checked with
.items
:You can also compare arrays directly:
Check that functions never return:
Generics can be used rather than references:
Distinguish between missing/null/optional properties:
Detect the difference between regular and
readonly
properties:Distinguish between classes with different constructors:
Known limitation: Intersection types can cause issues with
toEqualTypeOf
:To workaround for simple cases, you can use a mapped type:
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: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: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:
Another limitation: passing
this
references toexpectTypeOf
results in errors.: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 excludeunknown[]
from.parameters
and excludeunknown
from.returns
: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+.
Why is my assertion failing?
For complex types, an assertion might fail when it should if the
Actual
type contains a deeply-nested intersection type but theExpected
doesn't. In these cases you can use.branded
as described above:Where is
.toExtend
?A few people have asked for a method like
toExtend
- this is essentially whattoMatchTypeOf
is. There are some cases where it doesn't precisely match theextends
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 from using these beyond this warning: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 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 aMismatchInfo
type to try to make explicit what the expectation is. For example: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: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 (liketoBeString
,toBeNumber
,toBeVoid
, etc.) fail by resolving to a non-callable type when theActual
type under test doesn't match up. For example, the failure for an assertion likeexpectTypeOf(1).toBeString()
will look something like this: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.
Concrete "expected" objects vs type arguments
Error messages for an assertion like this:
Will be less helpful than for an assertion like this:
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 genericMismatch
type. So, where possible, use a type argument rather than a concrete type for.toEqualTypeOf
andtoMatchTypeOf
. If it's much more convenient to compare two concrete types, you can usetypeof
:Overloaded functions
Due to a TypeScript design limitation, the native TypeScript
Parameters<...>
andReturnType<...>
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).Within test frameworks
Vitest
expectTypeOf
is built in to vitest, so you can importexpectTypeOf
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.Limitations
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 helperParameters<...>
works. This may be improved in the future though (see related issue).expectTypeOf(this).toEqualTypeOf(this)
inside class methods does not work.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 functionsComparison
The key differences in this project are:
actual
andexpected
clear. This is helpful with complex types and assertions.expectTypeOf(...).not
any
(as well asunknown
andnever
) (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())
returnsany
, which could lead to errors. After giving it a proper return-type, you can add a test for this withexpect(parseFile).returns.not.toBeAny()
expectTypeOf(square).toMatchTypeOf<Shape>()
tsc
.Thanks to everyone who has helped with this over the years!
Full Changelog: mmkal/expect-type@v0.20.0...v1.0.0
Configuration
📅 Schedule: Branch creation - "before 4am on Monday" (UTC), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR was generated by Mend Renovate. View the repository job log.