chore(deps): update dependency expect-type to v1 - autoclosed #977
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.15.0
->^1.0.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
v0.20.0
Compare Source
Breaking changes
This change updates how overloaded functions are treated. Now,
.parameters
gives you a union of the parameter-tuples that a function can take. For example, given the following type:Behvaiour before:
Behaviour now:
There were similar changes for
.returns
,.parameter(...)
, and.toBeCallableWith
. Also, overloaded functions are now differentiated properly when using.branded.toEqualTypeOf
(this was a bug that it seems nobody found).See #83 for more details or look at the updated docs (including a new section called "Overloaded functions", which has more info on how this behaviour differs for TypeScript versions before 5.3).
What's Changed
1e37116
@internal
JSDoc tag (#104)4c40b07
overloads.ts
file (#107)5ee0181
0bbeffa
Full Changelog: mmkal/expect-type@v0.19.0...v0.20.0
v0.19.0
Compare Source
What's Changed
.omit()
to work similarly toOmit
by @aryaemami59 in https://github.com/mmkal/expect-type/pull/54test
import inREADME.md
by @aryaemami59 in https://github.com/mmkal/expect-type/pull/65Full Changelog: mmkal/expect-type@0.18.0...0.19.0
v0.18.0
Compare Source
What's Changed
.pick
and.omit
by @aryaemami59 in https://github.com/mmkal/expect-type/pull/51New Contributors
Full Changelog: mmkal/expect-type@v0.17.3...0.18.0
v0.17.3
Compare Source
907b8aa
v0.17.2
Compare Source
4b38117
Diff(truncated - scroll right!):
v0.17.1
Compare Source
.not
and.branded
togethercf38918
(this was actually documented in the v0.17.0 release but really it was only pushed here)
v0.17.0
Compare Source
#16 went in to - hopefully - significantly improve the error messages produce on failing assertions. Here's an example of how vitest's failing tests were improved:
Before:
After:
Docs copied from the readme about how to interpret these error messages
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 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 actually 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 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:
Will be less helpful than for an assertion like this:
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 genericMismatch
type. So, where possible, use a typearg rather than a concrete type for.toEqualTypeOf
andtoMatchTypeOf
. If it's much more convenient to compare two concrete types, you can usetypeof
:Kinda-breaking changes: essentially none, but technically,
.branded
no longer returns a "full"ExpectTypeOf
instance at compile-time. Previously you could do this:Now that won't work (and it was always slightly nonsensical), so you'd have to use
// @​ts-expect-error
instead ofnot
if you have a negated case where you needbranded
:What's Changed
New Contributors
Full Changelog: mmkal/expect-type@v0.16.0...v0.17.0
v0.16.0
Compare Source
What's Changed
this
parameters by @mmkal and @papb in https://github.com/mmkal/expect-type/pull/15Equal
to use the equality check fromReadonlyEquivalent
exclusively by @trevorade in https://github.com/mmkal/expect-type/pull/21Note that #21 has affected behavior for intersection types, which can result in (arguably) false errors:
Full Changelog: mmkal/expect-type@v0.15.0...v16.0.0
Configuration
📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
🚦 Automerge: Enabled.
♻ Rebasing: Whenever PR is behind base branch, 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.