In certain scenarios, my field can potentially contain both a schema and an object where this schema is defined by key. How can a guard effectively tackle this issue?
Below is an example of the code:
import * as z from 'zod';
import type { ZodTypeAny } from 'zod'
type Key = 'test' | 'test2' | 'test3'
type Schema = {
schema?: ZodTypeAny | {
[Property in Key]?: ZodTypeAny
}
}
const userSchema = z.object({
name: z.string(),
email: z.string(),
});
const getSchema = (key: Key, path: Schema) {
return path.schema?.[key] || path.schema
}
getSchema('test', { schema: {'test': userSchema}})
getSchema('test', { schema: userSchema})
You can test the code on TypeScript Playground here