Some definitions exist for an API (types are generated using protocol buffers). I'd rather not touch these.
One of these types, lets call it SomeInterfaceOutOfMyControl
has a property that is union type undefined. Like so:
interface SomeInterfaceOutOfMyControl {
someProperty: number | undefined
}
function someFuncOutOfMyControl(obj: SomeInterfaceOutOfMyControl) {}
I am trying to write a validator to really assert that the data is in the correct format. I am using zod for this.
const validator = z.object({
someProperty: z.optional(z.number()),
})
But the ts compiler doesn't seem to "understand" that number | undefined
is the same thing as an optional property. So I get this compiler error:
error TS2322: Type '{ someProperty?: number | undefined; }' is not assignable to type 'SomeInterfaceOutOfMyControl'. Property 'someProperty' is optional in type '{ someProperty?: number | undefined; }' but required in type 'SomeInterfaceOutOfMyControl'.
const object: SomeInterfaceOutOfMyControl = validator.parse(someData)
const validator = z.object({
someProperty: z.union([z.number(), z.undefined()]),
})
const someData = {} as any
const object = validator.parse(someData)
someFuncOutOfMyControl(object)
// Error on the line above:
// Argument of type '{ someProperty?: number | undefined; }' is not assignable to parameter of type 'SomeInterfaceOutOfMyControl'.
// Property 'someProperty' is optional in type '{ someProperty?: number | undefined; }' but required in type 'SomeInterfaceOutOfMyControl'.
How can I write the zod validation so that the inferred type becomes "correct" according to the interface? In other words, how do I write a validator for this?:
interface SomeInterfaceOutOfMyControl {
someProperty: number | undefined
}
I tried using a union:
const validator = z.object({
someProperty: z.union([z.number(), z.undefined()]),
})
But the result is the same...