diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index d6c2edb785..e8b98ad957 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -236,10 +236,9 @@ export type ObjectSchemaDefinition = { * This is conducive to the functionality of * [yup's `object.shape()` method](https://www.npmjs.com/package/yup#objectshapefields-object-nosortedges-arraystring-string-schema). */ -export type Shape = { - [P in keyof T]: P extends keyof U ? U[P] : T[P]; -} & - U; +export type Shape = + | ({ [P in keyof T]: P extends keyof U ? U[P] : T[P]; } & U) + | PreserveOptionals; export interface ObjectSchemaConstructor { (fields?: ObjectSchemaDefinition): ObjectSchema; @@ -512,8 +511,13 @@ type KeyOfUndefined = { [P in keyof T]-?: undefined extends T[P] ? P : never; }[keyof T]; +type PreserveNull = T extends null ? null : never; +type PreserveUndefined = T extends undefined ? undefined : never; +type PreserveOptionals = PreserveNull | PreserveUndefined; type Id = { [K in keyof T]: T[K] }; type RequiredProps = Pick>>; type NotRequiredProps = Partial>>; -type InnerInferType = T extends Array ? T[] : Id & RequiredProps> ; +type InnerInferType = + | (T extends Array ? T[] : Id & RequiredProps>) + | PreserveOptionals; type InferredArrayType = T extends Array ? U : T; diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index d200ad01d8..a780909d45 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -680,7 +680,7 @@ const definitionBC: yup.ObjectSchemaDefinition = { b: yup.string(), c: yup.number(), }; -const combinedSchema = yup.object(definitionAB).shape(definitionBC); // $ExpectType ObjectSchema> +const combinedSchema = yup.object(definitionAB).shape(definitionBC); // $ExpectType ObjectSchema<{ a: string; b: string; } & BC> // $ExpectError yup.object({ @@ -848,5 +848,35 @@ const resultingSchema2 = wrapper(true, yup.mixed().oneOf(['1', const arrayOfStringsSchema = yup.array().of(yup.string()); type ArrayOfStrings = yup.InferType; function returnTheArray(data: ArrayOfStrings): any[] { - return data; + return data; } + +const topLevelStringNullable = yup.string().nullable(); +const topLevelStringNullableExample: yup.InferType = null; + +const topLevelObjectNullable = yup.object().nullable(); +const topLevelObjectNullableExample: yup.InferType = null; + +const topLevelArrayNullable = yup.array().nullable(); +const topLevelArrayNullableExample: yup.InferType = null; + +const nestedNullableShape = yup.object().shape({ + foo: yup.object().nullable().shape({}) +}); +const nestedNullableShapeExample: yup.InferType = { + foo: null +}; + +const nestedShapeNullable = yup.object().shape({ + foo: yup.object().shape({}).nullable() +}); +const nestedShapeNullableExample: yup.InferType = { + foo: null +}; + +const nestedArrayNullable = yup.object().shape({ + foo: yup.array().nullable() +}); +const nestedArrayNullableExample: yup.InferType = { + foo: null +};