I’m using the zod
library for schema validation and have defined two schemas: FormFactorDevice
and FormFactor
. I’ve also implemented a selectFormFactorDevice
function to select a value from the FormFactorDevice
object based on a given deviceType
.
However, the return value of selectFormFactorDevice
is inferred as any
type, whereas I expect it to be string | undefined
since I’m using z.string()
as the fieldSchema
parameter.
Here’s the code:
export const FormFactorDevice = <T extends z.ZodTypeAny>(fieldSchema: T) =>
z.object({
all: z.optional(fieldSchema),
phone: z.optional(fieldSchema),
smalltablet: z.optional(fieldSchema),
tablet: z.optional(fieldSchema),
laptop: z.optional(fieldSchema),
desktop: z.optional(fieldSchema),
});
export const FormFactor = <Z extends z.ZodTypeAny>(fieldSchema: Z) =>
z.object({
isFormFactor: z.literal(true).default(true),
all: z.optional(fieldSchema),
landscape: z.optional(FormFactorDevice(fieldSchema)),
portrait: z.optional(FormFactorDevice(fieldSchema)),
});
const b = FormFactorDevice(z.string()).parse({
all: '100',
smalltablet: '200',
phone: '300',
});
export const selectFormFactorDevice = <T extends z.ZodTypeAny>(
formFactorDevice: z.infer<ReturnType<typeof FormFactorDevice<T>>>,
deviceType: 'all' | 'phone' | 'smalltablet' | 'tablet' | 'laptop' | 'desktop'
): z.infer<T> | undefined => {
return formFactorDevice[deviceType];
};
const d = selectFormFactorDevice(b, 'all'); // d is inferred as `any` type
How can I modify the selectFormFactorDevice
function to return the correct type (string | undefined
in this case)?
Note: I’ve tried using z.infer and ReturnType<typeof FormFactorDevice> to infer the correct type, but it doesn’t seem to work. The return value of selectFormFactorDevice is inferred as any type, whereas I expect it to be string | undefined since I’m using z.string() as the fieldSchema parameter.