-
Notifications
You must be signed in to change notification settings - Fork 933
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
Narrow type from array passed to mixed().oneOf() #1675
base: master
Are you sure you want to change the base?
Conversation
@jquense friendly bump, what do you think of the approach of this PR? |
@jquense closed #1230 just a couple of days ago: #1230 (comment) So it's possible this has been implemented in |
Mixed still doesn't narrow, but string does. I'm not convinced that mixed should narrow, it may make the type too restrictive. Still need to think about it a bit |
Is this new in
To me, it seems like usage of For example, in what case would a user want something different than const mixed = yup.mixed().oneOf(['abc', 'def'] as const); |
Regardless of whether it should narrow, import { mixed } from "yup";
type IsAny<T> = unknown extends T ? (T extends {} ? T : never) : never;
type NotAny<T> = T extends IsAny<T> ? never : T;
function notAny<T>(x: NotAny<T>) {}
// Without using .oneOf() retains the type of MixedSchema<null, AnyObject, undefined, ''>
const schemaWorking = mixed<null>().defined();
notAny(schemaWorking); // ✅ This type is not `any`
// Using .oneOf() sets the type to `any`
const schemaBroken = mixed<null>().oneOf([null]).defined();
notAny(schemaBroken); // 💥 Type is `any` |
Update on this? |
@jquense would you reconsider this PR? Would be great to be able to represent this properly: interface FormidableFile {
hashAlgorithm: false | "sha1" | "md5" | "sha256";
}
const formidableFileSchema: ObjectSchema<FormidableFile> = object({ // 💥 Currently errors, see below
hashAlgorithm: mixed()
.oneOf([false, 'sha1', 'md5', 'sha256'] as const)
.required(),
}) Currently this returns the following (confusing) error:
With the changes in this PR, the types match. |
Closes #1230
Broken: https://codesandbox.io/s/blissful-field-xw9kjn?file=/src/index.ts
Working: https://codesandbox.io/s/funny-fire-s1nh9v?file=/src/index.ts