Skip to content

Commit 3dd4a28

Browse files
committed
Add .extend to Zod enums
- Add `.extend` method to Enum class in Zod to allow extending enums with additional values
1 parent e308703 commit 3dd4a28

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

README.md

+9
Original file line numberDiff line numberDiff line change
@@ -1167,6 +1167,15 @@ You can also retrieve the list of options as a tuple with the `.options` propert
11671167
FishEnum.options; // ["Salmon", "Tuna", "Trout"];
11681168
```
11691169

1170+
** `.extend()` **
1171+
1172+
You can create supersets of a Zod enum with the `.extend` method.
1173+
1174+
```ts
1175+
const SalmonAndTrout = z.enum(["Salmon", "Trout"]);
1176+
const FishEnum = SalmonAndTrout.extend(["Tuna"]);
1177+
```
1178+
11701179
**`.exclude/.extract()`**
11711180

11721181
You can create subsets of a Zod enum with the `.exclude` and `.extract` methods.

src/__tests__/enum.test.ts

+11
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ test("error params", () => {
4141
}
4242
});
4343

44+
test("extends", () => {
45+
const italianFoods = ["Pasta", "Pizza"] as const;
46+
const ItalianEnum = z.enum(italianFoods);
47+
const FoodEnum = ItalianEnum.extend(["Tacos", "Burgers"]);
48+
49+
util.assertEqual<
50+
z.infer<typeof FoodEnum>,
51+
"Pasta" | "Pizza" | "Tacos" | "Burgers"
52+
>(true);
53+
});
54+
4455
test("extract/exclude", () => {
4556
const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const;
4657
const FoodEnum = z.enum(foods);

src/types.ts

+10
Original file line numberDiff line numberDiff line change
@@ -4407,6 +4407,16 @@ export class ZodEnum<T extends [string, ...string[]]> extends ZodType<
44074407
return enumValues as any;
44084408
}
44094409

4410+
extend<const ToExtend extends readonly [string, ...string[]]>(
4411+
values: ToExtend,
4412+
newDef: RawCreateParams = this._def
4413+
): ZodEnum<[...T, ...Writeable<ToExtend>]> {
4414+
return ZodEnum.create([...this._def.values, ...values], {
4415+
...this._def,
4416+
...newDef,
4417+
}) as any;
4418+
}
4419+
44104420
extract<ToExtract extends readonly [T[number], ...T[number][]]>(
44114421
values: ToExtract,
44124422
newDef: RawCreateParams = this._def

0 commit comments

Comments
 (0)