Skip to content
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

[@types/jest] Use optional generic in expect methods #34522

Closed
4 tasks done
G-Rath opened this issue Apr 6, 2019 · 0 comments · Fixed by #40092
Closed
4 tasks done

[@types/jest] Use optional generic in expect methods #34522

G-Rath opened this issue Apr 6, 2019 · 0 comments · Fixed by #40092

Comments

@G-Rath
Copy link
Contributor

G-Rath commented Apr 6, 2019

If you know how to fix the issue, make a pull request instead.

This is somewhat related to #27840, and could be superseded by #33705, but I decided to make an issue for this for the sake of tracking:

I think it could be useful if some of the methods in Jest had optional generics, in particular the expect matchers.

That way, we could explicitly denote the expected type of things, as well as the their value:

expect(obj).toStrictEqual<APIResponse>({ ... });
expect(value).toStrictEqual<string>('hello world');
expect(mock.fn).toHaveReturnedWith<number>(5);

// etc

Implementation example:

// before
toStrictEqual(expected: {}): R;
// after
toStrictEqual<T extends {} = {}>(expected: T): R;

// before
toHaveReturnedWith(expected: any): R;
// after
toHaveReturnedWith<T = any>(expected: T): R;

// etc

I have tried this locally, and it didn't seem to cause any problems.

The matchers relating to arrays and objects might take a bit more work. I know that the library factory.ts successfully strongly types the pattern of DeepPartial, doing the same thing as expect.objectContaining does, so those types might be useful here.

You could also do toHaveBeenCalledWith (and other function related matchers) with:

toHaveBeenCalledWith<T extends (...args: any) => any>(...params: Parameters<T>): R;

Regardless, I think it could be of great benefit to have any many any types use a generic instead.

I personally don't imagine this breaking too much, but in saying that I don't know Typescript well enough to predict how this might affect how TypeScript "perceives" the types if parameters are suddenly having a value of T rather than whatever they had before (where T equals what they previously had).


While I'm happy to try making a PR for this, DefinitelyTyped does explode my computer/IDE a bit, so it might be slow going 😂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant