jquense / yup

Dead simple Object schema validation
MIT License
22.93k stars 934 forks source link

ObjectSchema cast returns unassignable MakeKeysOptional type #2116

Closed Olesj-Bilous closed 1 year ago

Olesj-Bilous commented 1 year ago

As below, so in the sandbox:

import { ObjectSchema } from "yup";

function castRemoteObject<T extends object>(
  schema: ObjectSchema<T>
): (value: any) => T | null {
  return (value) => schema.nullable().default(null).json().cast(value); // Type 'Defined<MakeKeysOptional<T>> | null' is not assignable to type 'T | null'.
}

I'm not sure if this is intended behavior. I couldn't find it documented anywhere. From the type definitions, it seems MakeKeysOptional allows for all keys with potentially undefined values to be optional.

Does this mean I should take care not to iterate over keys that may not be defined when casting to T? Are there any other implications or best practices surrounding this?

jquense commented 1 year ago

I am fairly sure the purpose of the type is to allow the output type to be assignable to types that are missing properties we know are undefined, meaning optional fields produce a type that optionally has those properties, but yup should still output an object with all the schema keys, even if they are undefined. You'd need to double that tho

Olesj-Bilous commented 1 year ago

Alright, thanks for the clarification!