Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add zod.select #2333

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
- [Dates](#dates)
- [Zod enums](#zod-enums)
- [Native enums](#native-enums)
- [Selects](#selects)
- [Optionals](#optionals)
- [Nullables](#nullables)
- [Objects](#objects)
Expand Down Expand Up @@ -996,6 +997,35 @@ You can access the underlying object with the `.enum` property:
FruitEnum.enum.Apple; // "apple"
```

## Selects

```ts
const fishes: string[] = await getFishes();
const FishSelect = z.select(fishes);
type FishSelect = z.infer<typeof FishSelect>; // string
```

`z.select` allows to declare a schema with an arbitrary set of allowable values (not necessarily string), possibly populated in runtime.

**Const options**

Use `as const` to define specific options:

```ts
const KeyLengthSelect = z.select([512, 1024, 2048] as const);
type KeyLengthSelect = z.infer<typeof KeyLengthSelect>; // 512 | 1024 | 2048
```

For fixed sets of strings, consider using `z.enum()` instead as it provides better autocomplete options.

**Retrieving original options**

You can retrieve the list of options with the `.options` property:

```ts
FishSelect.options; // ["Salmon", "Tuna", "Trout"] - if that was coming from the database
```

## Optionals

You can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result.
Expand Down
30 changes: 30 additions & 0 deletions deno/lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
- [Dates](#dates)
- [Zod enums](#zod-enums)
- [Native enums](#native-enums)
- [Selects](#selects)
- [Optionals](#optionals)
- [Nullables](#nullables)
- [Objects](#objects)
Expand Down Expand Up @@ -995,6 +996,35 @@ You can access the underlying object with the `.enum` property:
FruitEnum.enum.Apple; // "apple"
```

## Selects

```ts
const fishes: string[] = await getFishes();
const FishSelect = z.select(fishes);
type FishSelect = z.infer<typeof FishSelect>; // string
```

`z.select` allows to declare a schema with an arbitrary set of allowable values (not necessarily string), possibly populated in runtime.

**Const options**

Use `as const` to define specific options:

```ts
const KeyLengthSelect = z.select([512, 1024, 2048] as const);
type KeyLengthSelect = z.infer<typeof KeyLengthSelect>; // 512 | 1024 | 2048
```

For fixed sets of strings, consider using `z.enum()` instead as it provides better autocomplete options.

**Retrieving original options**

You can retrieve the list of options with the `.options` property:

```ts
FishSelect.options; // ["Salmon", "Tuna", "Trout"] - if that was coming from the database
```

## Optionals

You can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result.
Expand Down
8 changes: 8 additions & 0 deletions deno/lib/ZodError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const ZodIssueCode = util.arrayToEnum([
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_select_value",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
Expand Down Expand Up @@ -68,6 +69,12 @@ export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase {
options: Primitive[];
}

export interface ZodInvalidSelectValueIssue extends ZodIssueBase {
received: any;
code: typeof ZodIssueCode.invalid_select_value;
options: readonly any[];
}

export interface ZodInvalidEnumValueIssue extends ZodIssueBase {
received: string | number;
code: typeof ZodIssueCode.invalid_enum_value;
Expand Down Expand Up @@ -150,6 +157,7 @@ export type ZodIssueOptionalMessage =
| ZodUnrecognizedKeysIssue
| ZodInvalidUnionIssue
| ZodInvalidUnionDiscriminatorIssue
| ZodInvalidSelectValueIssue
| ZodInvalidEnumValueIssue
| ZodInvalidArgumentsIssue
| ZodInvalidReturnTypeIssue
Expand Down
58 changes: 58 additions & 0 deletions deno/lib/__tests__/select.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// @ts-ignore TS6133
import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts";
const test = Deno.test;

import { util } from "../helpers/util.ts";
import * as z from "../index.ts";

test("infer type", () => {
const schema = z.select(["Red", "Green", "Blue", 10]);
type Schema = z.infer<typeof schema>;
util.assertEqual<Schema, string | number>(true);
});

test("infer const type", () => {
const schema = z.select(["Red", "Green", "Blue", 10] as const);
type Schema = z.infer<typeof schema>;
util.assertEqual<Schema, "Red" | "Green" | "Blue" | 10>(true);
});

test("get options", () => {
expect(z.select(["tuna", "trout"]).options).toEqual(["tuna", "trout"]);
});

test("parse string value", () => {
const result = z.select(["Red", "Green", "Blue"]).safeParse("Green");
expect(result.success).toEqual(true);
if (result.success) {
expect(result.data).toEqual("Green");
}
});

test("parse number value", () => {
const result = z.select([10, 20, 30]).safeParse(20);
expect(result.success).toEqual(true);
if (result.success) {
expect(result.data).toEqual(20);
}
});

test("parse missing value", () => {
const result = z.select(["Red", "Green", "Blue"]).safeParse("Violet");
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues[0].message).toEqual(
"Invalid value. Expected one of 3 options, received 'Violet'"
);
}
});

test("error params", () => {
const result = z
.select(["Red", "Green", "Blue"], { required_error: "REQUIRED" })
.safeParse(undefined);
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues[0].message).toEqual("REQUIRED");
}
});
3 changes: 3 additions & 0 deletions deno/lib/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ const errorMap: ZodErrorMap = (issue, _ctx) => {
issue.options
)}`;
break;
case ZodIssueCode.invalid_select_value:
message = `Invalid value. Expected one of ${issue.options.length} options, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(
issue.options
Expand Down
54 changes: 54 additions & 0 deletions deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4100,6 +4100,57 @@ export class ZodNativeEnum<T extends EnumLike> extends ZodType<
};
}

/////////////////////////////////////////
/////////////////////////////////////////
////////// //////////
////////// ZodSelect //////////
////////// //////////
/////////////////////////////////////////
/////////////////////////////////////////
export interface ZodSelectDef<T> extends ZodTypeDef {
values: readonly T[];
typeName: ZodFirstPartyTypeKind.ZodSelect;
}

function createZodSelect<T>(values: readonly T[], params?: RawCreateParams) {
return new ZodSelect<T>({
values,
typeName: ZodFirstPartyTypeKind.ZodSelect,
...processCreateParams(params),
});
}

export class ZodSelect<T> extends ZodType<T, ZodSelectDef<T>> {
_parse(input: ParseInput): ParseReturnType<this["_output"]> {
if (this._def.values.indexOf(input.data) === -1) {
const ctx = this._getOrReturnCtx(input);

if (input.data === undefined || input.data === null) {
addIssueToContext(ctx, {
expected: "unknown",
received: ctx.parsedType,
code: ZodIssueCode.invalid_type,
});
} else {
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_select_value,
options: this._def.values,
});
}

return INVALID;
}
return OK(input.data);
}

get options() {
return this._def.values;
}

static create = createZodSelect;
}

//////////////////////////////////////////
//////////////////////////////////////////
////////// //////////
Expand Down Expand Up @@ -4805,6 +4856,7 @@ export enum ZodFirstPartyTypeKind {
ZodFunction = "ZodFunction",
ZodLazy = "ZodLazy",
ZodLiteral = "ZodLiteral",
ZodSelect = "ZodSelect",
ZodEnum = "ZodEnum",
ZodEffects = "ZodEffects",
ZodNativeEnum = "ZodNativeEnum",
Expand Down Expand Up @@ -4890,6 +4942,7 @@ const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const selectType = ZodSelect.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
Expand Down Expand Up @@ -4948,6 +5001,7 @@ export {
preprocessType as preprocess,
promiseType as promise,
recordType as record,
selectType as select,
setType as set,
strictObjectType as strictObject,
stringType as string,
Expand Down
8 changes: 8 additions & 0 deletions src/ZodError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const ZodIssueCode = util.arrayToEnum([
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_select_value",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
Expand Down Expand Up @@ -68,6 +69,12 @@ export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase {
options: Primitive[];
}

export interface ZodInvalidSelectValueIssue extends ZodIssueBase {
received: any;
code: typeof ZodIssueCode.invalid_select_value;
options: readonly any[];
}

export interface ZodInvalidEnumValueIssue extends ZodIssueBase {
received: string | number;
code: typeof ZodIssueCode.invalid_enum_value;
Expand Down Expand Up @@ -150,6 +157,7 @@ export type ZodIssueOptionalMessage =
| ZodUnrecognizedKeysIssue
| ZodInvalidUnionIssue
| ZodInvalidUnionDiscriminatorIssue
| ZodInvalidSelectValueIssue
| ZodInvalidEnumValueIssue
| ZodInvalidArgumentsIssue
| ZodInvalidReturnTypeIssue
Expand Down
57 changes: 57 additions & 0 deletions src/__tests__/select.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// @ts-ignore TS6133
import { expect, test } from "@jest/globals";

import { util } from "../helpers/util";
import * as z from "../index";

test("infer type", () => {
const schema = z.select(["Red", "Green", "Blue", 10]);
type Schema = z.infer<typeof schema>;
util.assertEqual<Schema, string | number>(true);
});

test("infer const type", () => {
const schema = z.select(["Red", "Green", "Blue", 10] as const);
type Schema = z.infer<typeof schema>;
util.assertEqual<Schema, "Red" | "Green" | "Blue" | 10>(true);
});

test("get options", () => {
expect(z.select(["tuna", "trout"]).options).toEqual(["tuna", "trout"]);
});

test("parse string value", () => {
const result = z.select(["Red", "Green", "Blue"]).safeParse("Green");
expect(result.success).toEqual(true);
if (result.success) {
expect(result.data).toEqual("Green");
}
});

test("parse number value", () => {
const result = z.select([10, 20, 30]).safeParse(20);
expect(result.success).toEqual(true);
if (result.success) {
expect(result.data).toEqual(20);
}
});

test("parse missing value", () => {
const result = z.select(["Red", "Green", "Blue"]).safeParse("Violet");
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues[0].message).toEqual(
"Invalid value. Expected one of 3 options, received 'Violet'"
);
}
});

test("error params", () => {
const result = z
.select(["Red", "Green", "Blue"], { required_error: "REQUIRED" })
.safeParse(undefined);
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues[0].message).toEqual("REQUIRED");
}
});
3 changes: 3 additions & 0 deletions src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ const errorMap: ZodErrorMap = (issue, _ctx) => {
issue.options
)}`;
break;
case ZodIssueCode.invalid_select_value:
message = `Invalid value. Expected one of ${issue.options.length} options, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(
issue.options
Expand Down
Loading