import { z } from "zod";
// person vs animal discriminated union
const person = z.object({
entityType: z.literal("person"),
personName: z.string(),
age: z.number(),
});
const animal = z.object({
entityType: z.literal("animal"),
species: z.string(),
});
const personOrAnimal = z.union([person, animal]);
const examplePersonOrAnimal: z.infer<typeof personOrAnimal> = {
entityType: "animal",
species: "dog",
};
// location discriminated union
const country = z.object({
locationType: z.literal("country"),
locationName: z.string(),
});
const city = z.object({
locationType: z.literal("city"),
locationName: z.string(),
});
const location = z.union([country, city]);
const exampleLocation: z.infer<typeof location> = {
locationType: "city",
locationName: "New York",
};
// combined NxN union
const entityAtLocation = z.intersection(personOrAnimal, location);
const exampleEntityAtLocation: z.infer<typeof entityAtLocation> = {
entityType: "animal",
species: "dog",
locationType: "city",
locationName: "New York",
};
import { z } from "zod";
// person vs animal discriminated union
const person = z.object({
entityType: z.literal("person"),
personName: z.string(),
age: z.number(),
});
const animal = z.object({
entityType: z.literal("animal"),
species: z.string(),
});
const personOrAnimal = z.union([person, animal]);
const examplePersonOrAnimal: z.infer<typeof personOrAnimal> = {
entityType: "animal",
species: "dog",
};
// location discriminated union
const country = z.object({
locationType: z.literal("country"),
locationName: z.string(),
});
const city = z.object({
locationType: z.literal("city"),
locationName: z.string(),
});
const location = z.union([country, city]);
const exampleLocation: z.infer<typeof location> = {
locationType: "city",
locationName: "New York",
};
// combined NxN union
const entityAtLocation = z.intersection(personOrAnimal, location);
const exampleEntityAtLocation: z.infer<typeof entityAtLocation> = {
entityType: "animal",
species: "dog",
locationType: "city",
locationName: "New York",
};