Skip to content

Commit

Permalink
nonNullable disallows undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
sezanzeb committed Apr 2, 2024
1 parent 991750c commit a54ef93
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 4 deletions.
10 changes: 9 additions & 1 deletion deno/lib/__tests__/nonNullable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,21 @@ test("parses a number correctly using z.nonNullable(...)", () => {
});

test("fails is passed null", () => {
const a = z.nullable(z.number()).nonNullable();
const a = z.nullable(z.any()).nonNullable();

expect(() => {
a.parse(null);
}).toThrow(z.ZodError)
});

test("fails is passed undefined", () => {
const a = z.nullable(z.any()).nonNullable();

expect(() => {
a.parse(undefined);
}).toThrow(z.ZodError)
});

test("unwrap", () => {
const unwrapped = z.any().nonNullable().unwrap();
expect(unwrapped).toBeInstanceOf(z.ZodAny);
Expand Down
5 changes: 4 additions & 1 deletion deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4480,7 +4480,10 @@ export class ZodNonNullable<T extends ZodTypeAny> extends ZodType<
> {
_parse(input: ParseInput): ParseReturnType<this["_output"]> {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
if (
parsedType === ZodParsedType.null ||
parsedType === ZodParsedType.undefined
) {
const { ctx } = this._processInputParams(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
Expand Down
10 changes: 9 additions & 1 deletion src/__tests__/nonNullable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,21 @@ test("parses a number correctly using z.nonNullable(...)", () => {
});

test("fails is passed null", () => {
const a = z.nullable(z.number()).nonNullable();
const a = z.nullable(z.any()).nonNullable();

expect(() => {
a.parse(null);
}).toThrow(z.ZodError)
});

test("fails is passed undefined", () => {
const a = z.nullable(z.any()).nonNullable();

expect(() => {
a.parse(undefined);
}).toThrow(z.ZodError)
});

test("unwrap", () => {
const unwrapped = z.any().nonNullable().unwrap();
expect(unwrapped).toBeInstanceOf(z.ZodAny);
Expand Down
5 changes: 4 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4480,7 +4480,10 @@ export class ZodNonNullable<T extends ZodTypeAny> extends ZodType<
> {
_parse(input: ParseInput): ParseReturnType<this["_output"]> {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
if (
parsedType === ZodParsedType.null ||
parsedType === ZodParsedType.undefined
) {
const { ctx } = this._processInputParams(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
Expand Down

0 comments on commit a54ef93

Please sign in to comment.