jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

yup.string() -> .cast() should return null when input value is not in the .oneOf array #2132

Closed SneakySensei closed 1 year ago

SneakySensei commented 1 year ago

Describe the bug A schema like yup.string().oneOf(["WARNING", "INFO", "ERROR"]).nullable().default(null) should cast a random string into null but instead it return the input value.

To Reproduce Here's the snippet I've written. https://codesandbox.io/s/vigilant-bouman-7ndf9h?file=/src/index.ts Hover over the parsedValue and you'll see that TS is expecting this to be the correct type even though it isn't.

Expected behavior I get that .cast() is just to coerce values to a certain type and technically a random string is already a string so coerce is not doing anything. But the TS type returned from cast for this schema is "WARNING" | "INFO" | "ERROR" | null so I think it's more appropriate if a random string is coerced to null in this case.

For now I have to add a redundant check in a transform which transforms random strings to null but I think this should be happening part of .oneOf itself.

jquense commented 1 year ago

For now I have to add a redundant check in a transform which transforms random strings to null but I think this should be happening part of .oneOf itself.

It's not a redundant check, it's logic specific to your use-case, If you want incorrect values to be turned into null this is the correct way to do it.