zod
zod copied to clipboard
Object with Generic Properties makes the properties optional
In the following code, if I use generic parameters to create some validators, as in ValidatorFactory
, this makes all the non static properties optional. Is this a limitation on Typescript or Zod?
import { AnyZodObject, ZodType, z } from "zod";
type allowedStandardStringEnum=Record<string, string>
type EnumValues<Enum extends allowedStandardStringEnum> = Enum[keyof Enum]
function stringEnumValidator<Enum extends allowedStandardStringEnum>(enumParam:Enum):ZodType<EnumValues<Enum>>{
return z.nativeEnum(enumParam);
}
function ValidatorFactory<StateEnum extends allowedStandardStringEnum, ZodDataObject extends AnyZodObject>(
states:StateEnum,
validator:ZodDataObject,
){
return z.object({
staticProp: z.string(),
currentState : stringEnumValidator(states),
dataForFunction : z.unknown(),
stateData : validator,
})
}
type FactoryReturn<StateEnum extends allowedStandardStringEnum, ZodDataObject extends AnyZodObject>=z.infer<ReturnType<typeof ValidatorFactory<StateEnum,ZodDataObject>>>
function execution<StateEnum extends allowedStandardStringEnum, ZodDataObject extends AnyZodObject>(instance:FactoryReturn<StateEnum, ZodDataObject>){
let staticProp=instance.staticProp // Correct
let currentState=instance.currentState // Incorrect
let dataForFunction=instance.dataForFunction // Incorrect
let stateData=instance.stateData // Incorrect
}
I believe it may also be similar to https://github.com/colinhacks/zod/issues/2077
Also believing that it may be caused by https://github.com/colinhacks/zod/issues/3330, I can verify that "strict":true
has been set in tsconfig.json
Thanks in Advance for any help
Same here, but then I found out compilerOptions.strictNullChecks
was set to false
by another tsconfig.json
file I extend. Setting "strict": true, "strictNullChecks": true
solve my problem. @agarwalvaibhav0211 I hope this helpful.
@YogaLin, While debugging further, I came across something weird, that it's actually the reverse for me. Setting "strict":true
causes the data to be optional while setting "strict":false
makes it required as expected. I've created 2 live codes you can check below (you can check line 55 on src/index.ts
and line 11 of tsconfig.json
in both sandboxes). Do you know if there is something wrong with what I'm doing??