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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

expectTypeOf allows an incorrect any value instead of the specified type #38

Closed
kwangure opened this issue Oct 2, 2023 · 2 comments 路 Fixed by #16
Closed

expectTypeOf allows an incorrect any value instead of the specified type #38

kwangure opened this issue Oct 2, 2023 · 2 comments 路 Fixed by #16

Comments

@kwangure
Copy link

kwangure commented Oct 2, 2023

When I use expectTypeOf, I expect it to fail when I pass any as input. For example, toBeString() should strictly only allow strings and not any other type...including any.

expectTypeOf(1).toBeString(); //  Fails 馃憤
expectTypeOf(1 as any).toBeString(); // Passes 馃憥

This is particular useful in cases when your types reason about any, I need to strictly know that a type will fail if its any or not. For example:

type IsAny<T> = 0 extends 1 & T ? true : false;

export type CustomType<T> = IsAny<T> extends true ? number: any;

If I use CustomType somewhere, I'd like to test expectTypeOf(value).toBeNumber(); and have it fail if it's any when I don't expect it to be.

This issue was originally opened at vitest-dev/vitest#4205.

@mmkal
Copy link
Owner

mmkal commented Oct 2, 2023

This will be fixed by #16. And looks to be a duplicate of #32. If you're using expect-type directly, you can try the next dist tag now. The version in vitest will be bumped by vitest-dev/vitest#4206. Simplest thing to do will just be to wait for that.

@mmkal mmkal mentioned this issue Oct 2, 2023
2 tasks
@mmkal
Copy link
Owner

mmkal commented Oct 2, 2023

Copy-pasted from docs added in #16, this will be the new behaviour:

.toBe... methods allow for types which extend the expected type:

expectTypeOf<number>().toBeNumber()
expectTypeOf<1>().toBeNumber()

expectTypeOf<any[]>().toBeArray()
expectTypeOf<number[]>().toBeArray()

expectTypeOf<string>().toBeString()
expectTypeOf<'foo'>().toBeString()

expectTypeOf<boolean>().toBeBoolean()
expectTypeOf<true>().toBeBoolean()

.toBe... methods protect against any:

const goodIntParser = (s: string) => Number.parseInt(s, 10)
const badIntParser = (s: string) => JSON.parse(s) // uh-oh - works at runtime if the input is a number, but return 'any'

expectTypeOf(goodIntParser).returns.toBeNumber()
// @ts-expect-error - if you write a test like this, `.toBeNumber()` will let you know your implementation returns `any`.
expectTypeOf(badIntParser).returns.toBeNumber()

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.

2 participants