Descrição
Suponha que temos o seguinte conjunto de interfaces TypeScript:
// Indexed type for type-specific fields
interface RichTextMap {
text?: { text: string };
equation?: { equation: string };
mention?: { mention: string };
}
// Main RichText interface with indexed types
interface RichTextBase {
type: "text" | "mention" | "equation";
annotations: any;
plain_text: string;
href: string | null;
}
type RichText = RichTextBase & (RichTextMap[RichTextBase["type"]] & {});
O RichText
tipo deve permitir os objetos da seguinte forma:
const text = {
type: "text",
annotations: {},
plain_text: "",
href: null,
text: { text: "" }
}
const mention = {
type: "mention",
annotations: {},
plain_text: "",
href: null,
mention: { mention: "" }
}
Declaração do problema
Preciso definir zod
o esquema para os objetos mencionados.
Minha compreensão zod
ainda precisa melhorar, mas até agora consegui chegar à seguinte solução:
const RichTextSchema = z
.object({
type: z.enum(["text", "mention", "equation"]),
annotations: z.object({}).passthrough(),
plain_text: z.string(),
href: z.string().url().nullable(),
});
const TextRichTextSchema = RichTextSchema.extend({
text: z.object({ text: z.string() }).optional(),
})
const MentionRichTextSchema = RichTextSchema.extend({
mention: z.object({ mention: z.string() }).optional(),
})
const EquationRichTextSchema = RichTextSchema.extend({
equation: z.object({ equation: z.string() }).optional(),
})
Agora, o problema com essa abordagem é que estou criando três esquemas diferentes e terei que descobrir qual deles chamar em tempo de execução. Enquanto o tipo de interface é genérico o suficiente para encaixar objetos diferentes em um único tipo.
Pergunta: Gostaria de saber se há uma maneira de alterar o RichTextSchema
para poder validar contra os tipos de interface mencionados acima. Essencialmente, mantendo apenas um único objeto de esquema que valida objetos diferentes do exemplo.