There are some predefined definitions for an API (with types generated using protocol buffers). I prefer not to modify these.
One of the types, which we'll refer to as SomeInterfaceOutOfMyControl
, includes a property that is a union type of undefined. Here's how it looks:
interface SomeInterfaceOutOfMyControl {
someProperty: number | undefined
}
function someFuncOutOfMyControl(obj: SomeInterfaceOutOfMyControl) {}
I am attempting to create a validator to ensure that the data adheres to the correct format. For this purpose, I am utilizing zod.
const validator = z.object({
someProperty: z.optional(z.number()),
})
However, the TypeScript compiler seems to be confused about the fact that number | undefined
is essentially the same as an optional property. Hence, I encounter 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 adjust the zod validation so that the inferred type aligns with the interface correctly? In other words, how do I create a validator for this?:
interface SomeInterfaceOutOfMyControl {
someProperty: number | undefined
}
I attempted using a union:
const validator = z.object({
someProperty: z.union([z.number(), z.undefined()]),
})
However, the outcome remains the same...