-
-
Notifications
You must be signed in to change notification settings - Fork 7
chore(deps): update devdependency expect-type to v1 #631
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
Important Review skippedIgnore keyword(s) in the title. ⛔ Ignored keywords (1)
Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Note Free review on us!CodeRabbit is offering free reviews until Wed Jan 15 2025 to showcase some of the refinements we've made. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
01c4d27 to
012ba30
Compare
012ba30 to
850cd6b
Compare
850cd6b to
bd5778f
Compare
bd5778f to
44309ef
Compare
44309ef to
21dc7bc
Compare
21dc7bc to
17193c1
Compare
17193c1 to
47787dd
Compare
47787dd to
f8e3c8d
Compare
f8e3c8d to
1ec184e
Compare
f264af9 to
d7f3725
Compare
e034296 to
751091d
Compare
751091d to
8e249d2
Compare
8e249d2 to
db495b8
Compare
879f8f8 to
9c8b979
Compare
9c8b979 to
4f73ce9
Compare
945b2b6 to
35cedc8
Compare
35cedc8 to
fe6f8a6
Compare
fe6f8a6 to
15382d8
Compare
15382d8 to
c1b7352
Compare
f801c80 to
8ce6f53
Compare
d875073 to
1774230
Compare
1c26e91 to
dfa0734
Compare
cb822b7 to
64807e4
Compare
711e0ba to
3c06970
Compare
3c06970 to
fba2202
Compare
fba2202 to
e60143d
Compare
b64b67b to
3886187
Compare
3886187 to
6aee7c6
Compare
6aee7c6 to
037d8b0
Compare
525b4b7 to
b6aab4c
Compare
b6aab4c to
e0e93c0
Compare
e0e93c0 to
74f8991
Compare
74f8991 to
ee93f76
Compare
ee93f76 to
5f4557d
Compare
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
This PR contains the following updates:
0.15.0->1.3.0Release Notes
mmkal/expect-type (expect-type)
v1.3.0Compare Source
What's Changed
Full Changelog: mmkal/expect-type@v1.2.2...v1.3.0
v1.2.2Compare Source
7d6fa420c9d8c27ff4f4d1149186v1.2.1Compare Source
0c5a05dv1.2.0Compare Source
What's Changed
❗
toMatchTypeOfis now deprecated. There are no plans to remove it any time soon, so it's not critical to immediately remove usages, but if you want to avoid squigglies in IDEs complaining about deprecations, here's what you should do:If you have an assertion like this:
There are a few options for upgrading it. The easiest is
toExtendwhich is identical to the behaviour oftoMatchTypeOf:This will work in all cases. But, there is now a stricter option that will work in many cases and be slightly more likely to catch things like
readonlyproperties matching:But, as the name suggests, this will only work on plain object types, it will fail for union types, and some other complex types.
If you have code like this:
You'll need to use
typeofbecausetoExtendandtoMatchObjectTypedo not accept argumentsFull Changelog: mmkal/expect-type@v1.1.0...v1.2.0
v1.1.0Compare Source
What's Changed
.toBeBigInt()by @aryaemami59 in #123Full Changelog: mmkal/expect-type@v1.0.0...v1.1.0
v1.0.0Compare 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:
.pickand.omitthanks to @aryaemami59.brandedhelper for the old behaviour. Also support functionthisparameters - 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
expectTypeOfmethod 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:.toEqualTypeOfcan 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):.toEqualTypeOfsucceeds for objects with different values, but the same type:.toEqualTypeOffails on excess properties:To allow for extra properties, use
.toMatchTypeOf. This is roughly equivalent to anextendsconstraint in a function type argument.:.toEqualTypeOfand.toMatchTypeOfboth fail on missing properties:Another example of the difference between
.toMatchTypeOfand.toEqualTypeOf, using generics..toMatchTypeOfcan be used for "is-a" relationships:Assertions can be inverted with
.not:.notcan be easier than relying on// @​ts-expect-error:Catch any/unknown/never types:
.toEqualTypeOfdistinguishes between deeply-nestedanyandunknownproperties:You can test for basic JavaScript types:
.toBe...methods allow for types that extend the expected type:.toBe...methods protect againstany:Nullable types:
More
.notexamples:Detect assignability of unioned types:
Use
.extractand.excludeto narrow down complex union types:.extractand.excludereturn never if no types remain after exclusion:Use
.pickto pick a set of properties from an object:Use
.omitto remove a set of properties from an object:Make assertions about object properties:
.toEqualTypeOfcan be used to distinguish between functions:But often it's preferable to use
.parametersor.returnsfor more specific function assertions:Up to ten overloads will produce union types for
.parametersand.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:.toBeCallableWithallows for overloads. You can also use it to narrow down the return type for given input parameters.:.toBeCallableWithreturns a type that can be used to narrow down the return type for given input parameters.:.toBeCallableWithcan be used to narrow down the parameters of a function:You can't use
.toBeCallableWithwith.not- you need to use ts-expect-error::You can also check type guards & type assertions:
Assert on constructor parameters:
Constructor overloads:
Check function
thisparameters:Distinguish between functions with different
thisparameters: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
readonlyproperties: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
.brandedhelper. 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.brandedbecause it deeply transforms the Actual and Expected types into a pseudo-AST:Be careful with
.brandedfor 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
thisreferences toexpectTypeOfresults 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[]) => unknownwill excludeunknown[]from.parametersand excludeunknownfrom.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
Actualtype contains a deeply-nested intersection type but theExpecteddoesn't. In these cases you can use.brandedas described above:Where is
.toExtend?A few people have asked for a method like
toExtend- this is essentially whattoMatchTypeOfis. There are some cases where it doesn't precisely match theextendsoperator 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,
.toEqualTypeOfand.toMatchTypeOfuse 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 aMismatchInfotype 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 theActualtype 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 callablepart 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 genericMismatchtype. So, where possible, use a type argument rather than a concrete type for.toEqualTypeOfandtoMatchTypeOf. 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
expectTypeOfis built in to vitest, so you can importexpectTypeOffrom 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.
.brandin these cases - and accept the performance hit that it comes with.toBeCallableWithwill 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..parameterand.parametershelpers. 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:
tsdis a CLI that runs the TypeScript type checker over assertionsts-expectexports several generic helper types to perform type assertionsdtslintdoes type checks via comment directives and tslinttype-pluscomes with various type and runtime TypeScript assertionsstatic-type-asserttype assertion functionsComparison
The key differences in this project are:
actualandexpectedclear. This is helpful with complex types and assertions.expectTypeOf(...).notany(as well asunknownandnever) (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.0Compare Source
Breaking changes
This change updates how overloaded functions are treated. Now,
.parametersgives 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@internalJSDoc tag (#104)4c40b07overloads.tsfile (#107)5ee01810bbeffaFull Changelog: mmkal/expect-type@v0.19.0...v0.20.0
v0.19.0Compare Source
What's Changed
.omit()to work similarly toOmitby @aryaemami59 in #54testimport inREADME.mdby @aryaemami59 in #65Full Changelog: mmkal/expect-type@0.18.0...0.19.0
v0.18.0Compare Source
What's Changed
.pickand.omitby @aryaemami59 in #51New Contributors
Full Changelog: mmkal/expect-type@v0.17.3...0.18.0
v0.17.3Compare Source
907b8aav0.17.2Compare Source
4b38117Diff(truncated - scroll right!):
test('toEqualTypeOf with tuples', () => { const assertion = `expectTypeOf<[[number], [1], []]>().toEqualTypeOf<[[number], [2], []]>()` expect(tsErrors(assertion)).toMatchInlineSnapshot(` - "test/test.ts:999:999 - error TS2344: Type '[[number], [2], []]' does not satisfy the constraint '{ [x: number]: { [x: number]: number; [iterator]: (() => IterableIterator<1>) | (() => IterableIterator<number>) | (() => IterableIterator<never>); [unscopables]: (() => { copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; }) | (() => { copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; }) | (() => { copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; }); length: 0 | 1; toString: ... truncated!!!!'. - Types of property 'sort' are incompatible. - Type '(compareFn?: ((a: [] | [number] | [2], b: [] | [number] | [2]) => number) | undefined) => [[number], [2], []]' is not assignable to type '\\"Expected: function, Actual: function\\"'. + "test/test.ts:999:999 - error TS2344: Type '[[number], [2], []]' does not satisfy the constraint '{ 0: { 0: number; }; 1: { 0: \\"Expected: literal number: 2, Actual: literal number: 1\\"; }; 2: {}; }'. + The types of '1[0]' are incompatible between these types. + Type '2' is not assignable to type '\\"Expected: literal number: 2, Actual: literal number: 1\\"'. 999 expectTypeOf<[[number], [1], []]>().toEqualTypeOf<[[number], [2], []]>() ~~~~~~~~~~~~~~~~~~~" `) })v0.17.1Compare Source
.notand.brandedtogethercf38918(this was actually documented in the v0.17.0 release but really it was only pushed here)
v0.17.0Compare 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,
.toEqualTypeOfand.toMatchTypeOfuse 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 aMismatchInfotype 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,toBeVoidetc.) fail by resolving to a non-callable type when theActualtype 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 callablepart 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 genericMismatchtype. So, where possible, use a typearg rather than a concrete type for.toEqualTypeOfandtoMatchTypeOf. If it's much more convenient to compare two concrete types, you can usetypeof:Kinda-breaking changes: essentially none, but technically,
.brandedno longer returns a "full"ExpectTypeOfinstance 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-errorinstead ofnotif 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.0Compare Source
What's Changed
thisparameters by @mmkal and @papb in #15Equalto use the equality check fromReadonlyEquivalentexclusively by @trevorade in #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 - "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.