After reviewing your feedback, it seems like you are aiming to ensure that your schema aligns with the Method
type from axios. Here is a suggestion on how you can achieve this:
import { z } from 'zod';
import type { Method } from 'axios';
const methods: z.ZodType<Method> = z.enum(['get', 'GET', ...]);
This approach will enforce that the schema on the right side of the expression can only parse valid axios Method
results. However, achieving more than this may be challenging unless axios
also provides an array containing the corresponding method strings for the Method
type.
The original concept you were exploring, such as using z.something(<type here>)
, won't work due to zod utilizing actual runtime objects, and types like Method
not existing at runtime. If axios
supplied an array of methods, then it would be feasible to generate your methods
schema based on that (with potential type casting).
One limitation of the initial approach is evident when defining the schema with a single value like so:
const methods z.ZodType<Method> = z.enum(['get']);
This is permitted in TypeScript because of how types function. Even though the schema only accepts 'get'
, it can still be assigned due to the subtype relationship with the larger union type defined by Method
.
Considering these factors, another option could involve redeclaring all Method
values to create a schema that encompasses all possibilities:
import { z } from "zod";
import { Method } from "axios";
const METHOD_MAP: { [K in Method]: null } = {
get: null,
GET: null,
delete: null,
DELETE: null,
// list continues...
};
const METHODS = (Object.keys(METHOD_MAP) as unknown) as readonly [
Method,
...Method[]
];
const methods: z.ZodType<Method> = z.enum(METHODS);
The type assertion for METHODS
is safe since METHOD_MAP
is internal, preventing any missing Method
values. As a result, the compiled schema guarantees parsing of all Method
values while adhering to compile-time constraints.