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

nonNullable to disallow null #3141

Closed
wants to merge 2 commits 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
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,31 @@ const nullableString = stringSchema.nullable();
nullableString.unwrap() === stringSchema; // true
```

## NonNullables

You can also make something NonNullable, using `z.nonNullable()`.

```ts
const nullableString = z.nonNullable(z.any());
nullableString.parse("asdf"); // => "asdf"
nullableString.parse(null); // fails
```

Or use the `.nonNullable()` method.

```ts
const E = z.any().nonNullable();
type E = z.infer<typeof E>; // NonNullable<any>
```

Extract the inner schema with `.unwrap()`.

```ts
const stringSchema = z.any();
const nullableString = stringSchema.nonNullable();
nullableString.unwrap() === stringSchema; // true
```

## Objects

```ts
Expand Down
25 changes: 25 additions & 0 deletions deno/lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,31 @@ const nullableString = stringSchema.nullable();
nullableString.unwrap() === stringSchema; // true
```

## NonNullables

You can also make something NonNullable, using `z.nonNullable()`.

```ts
const nullableString = z.nonNullable(z.any());
nullableString.parse("asdf"); // => "asdf"
nullableString.parse(null); // fails
```

Or use the `.nonNullable()` method.

```ts
const E = z.any().nonNullable();
type E = z.infer<typeof E>; // NonNullable<any>
```

Extract the inner schema with `.unwrap()`.

```ts
const stringSchema = z.any();
const nullableString = stringSchema.nonNullable();
nullableString.unwrap() === stringSchema; // true
```

## Objects

```ts
Expand Down
2 changes: 2 additions & 0 deletions deno/lib/__tests__/firstparty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ test("first party switch", () => {
break;
case z.ZodFirstPartyTypeKind.ZodNullable:
break;
case z.ZodFirstPartyTypeKind.ZodNonNullable:
break;
case z.ZodFirstPartyTypeKind.ZodDefault:
break;
case z.ZodFirstPartyTypeKind.ZodCatch:
Expand Down
40 changes: 40 additions & 0 deletions deno/lib/__tests__/nonNullable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// @ts-ignore TS6133
import { expect } from "https://deno.land/x/[email protected]/mod.ts";
const test = Deno.test;

import * as z from "../index.ts";

test("parses a number correctly using z....nonNullable()", () => {
const a = z.nullable(z.number()).nonNullable();
type a = z.infer<typeof a>;
const foo: a = a.parse(5);
expect(foo).toEqual(5);
});

test("parses a number correctly using z.nonNullable(...)", () => {
const a = z.nonNullable(z.any());
type a = z.infer<typeof a>;
const foo: a = a.parse(5);
expect(foo).toEqual(5);
});

test("fails is passed null", () => {
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);
});
1 change: 1 addition & 0 deletions deno/lib/helpers/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ export const ZodParsedType = util.arrayToEnum([
"never",
"map",
"set",
"nonNullable"
]);

export type ZodParsedType = keyof typeof ZodParsedType;
Expand Down
60 changes: 60 additions & 0 deletions deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,9 @@ export abstract class ZodType<
this.isOptional = this.isOptional.bind(this);
}

nonNullable(): ZodNonNullable<this> {
return ZodNonNullable.create(this, this._def) as any;
}
optional(): ZodOptional<this> {
return ZodOptional.create(this, this._def) as any;
}
Expand Down Expand Up @@ -4455,6 +4458,59 @@ export class ZodOptional<T extends ZodTypeAny> extends ZodType<
};
}

//////////////////////////////////////////
//////////////////////////////////////////
////////// ///////////
////////// ZodNonNullable ///////////
////////// ///////////
//////////////////////////////////////////
//////////////////////////////////////////
export interface ZodNonNullableDef<T extends ZodTypeAny = ZodTypeAny>
extends ZodTypeDef {
innerType: T;
typeName: ZodFirstPartyTypeKind.ZodNonNullable;
}

export type ZodNonNullableType<T extends ZodTypeAny> = ZodNonNullable<T>;

export class ZodNonNullable<T extends ZodTypeAny> extends ZodType<
NonNullable<T["_output"]>,
ZodNonNullableDef<T>,
T["_input"]
> {
_parse(input: ParseInput): ParseReturnType<this["_output"]> {
const parsedType = this._getType(input);
if (
parsedType === ZodParsedType.null ||
parsedType === ZodParsedType.undefined
) {
const { ctx } = this._processInputParams(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nonNullable,
received: ctx.parsedType,
});
return INVALID;
}
return this._def.innerType._parse(input);
}

unwrap() {
return this._def.innerType;
}

static create = <T extends ZodTypeAny>(
type: T,
params?: RawCreateParams
): ZodNonNullable<T> => {
return new ZodNonNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNonNullable,
...processCreateParams(params),
}) as any;
};
}

///////////////////////////////////////////
///////////////////////////////////////////
////////// //////////
Expand Down Expand Up @@ -4927,6 +4983,7 @@ export enum ZodFirstPartyTypeKind {
ZodEffects = "ZodEffects",
ZodNativeEnum = "ZodNativeEnum",
ZodOptional = "ZodOptional",
ZodNonNullable = "ZodNonNullable",
ZodNullable = "ZodNullable",
ZodDefault = "ZodDefault",
ZodCatch = "ZodCatch",
Expand Down Expand Up @@ -4965,6 +5022,7 @@ export type ZodFirstPartySchemaTypes =
| ZodNativeEnum<any>
| ZodOptional<any>
| ZodNullable<any>
| ZodNonNullable<any>
| ZodDefault<any>
| ZodCatch<any>
| ZodPromise<any>
Expand Down Expand Up @@ -5015,6 +5073,7 @@ const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const nonNullableType = ZodNonNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = () => stringType().optional();
Expand Down Expand Up @@ -5055,6 +5114,7 @@ export {
nanType as nan,
nativeEnumType as nativeEnum,
neverType as never,
nonNullableType as nonNullable,
nullType as null,
nullableType as nullable,
numberType as number,
Expand Down
2 changes: 2 additions & 0 deletions src/__tests__/firstparty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ test("first party switch", () => {
break;
case z.ZodFirstPartyTypeKind.ZodNullable:
break;
case z.ZodFirstPartyTypeKind.ZodNonNullable:
break;
case z.ZodFirstPartyTypeKind.ZodDefault:
break;
case z.ZodFirstPartyTypeKind.ZodCatch:
Expand Down
39 changes: 39 additions & 0 deletions src/__tests__/nonNullable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// @ts-ignore TS6133
import { expect, test } from "@jest/globals";

import * as z from "../index";

test("parses a number correctly using z....nonNullable()", () => {
const a = z.nullable(z.number()).nonNullable();
type a = z.infer<typeof a>;
const foo: a = a.parse(5);
expect(foo).toEqual(5);
});

test("parses a number correctly using z.nonNullable(...)", () => {
const a = z.nonNullable(z.any());
type a = z.infer<typeof a>;
const foo: a = a.parse(5);
expect(foo).toEqual(5);
});

test("fails is passed null", () => {
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);
});
1 change: 1 addition & 0 deletions src/helpers/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ export const ZodParsedType = util.arrayToEnum([
"never",
"map",
"set",
"nonNullable"
]);

export type ZodParsedType = keyof typeof ZodParsedType;
Expand Down
60 changes: 60 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,9 @@ export abstract class ZodType<
this.isOptional = this.isOptional.bind(this);
}

nonNullable(): ZodNonNullable<this> {
return ZodNonNullable.create(this, this._def) as any;
}
optional(): ZodOptional<this> {
return ZodOptional.create(this, this._def) as any;
}
Expand Down Expand Up @@ -4455,6 +4458,59 @@ export class ZodOptional<T extends ZodTypeAny> extends ZodType<
};
}

//////////////////////////////////////////
//////////////////////////////////////////
////////// ///////////
////////// ZodNonNullable ///////////
////////// ///////////
//////////////////////////////////////////
//////////////////////////////////////////
export interface ZodNonNullableDef<T extends ZodTypeAny = ZodTypeAny>
extends ZodTypeDef {
innerType: T;
typeName: ZodFirstPartyTypeKind.ZodNonNullable;
}

export type ZodNonNullableType<T extends ZodTypeAny> = ZodNonNullable<T>;

export class ZodNonNullable<T extends ZodTypeAny> extends ZodType<
NonNullable<T["_output"]>,
ZodNonNullableDef<T>,
T["_input"]
> {
_parse(input: ParseInput): ParseReturnType<this["_output"]> {
const parsedType = this._getType(input);
if (
parsedType === ZodParsedType.null ||
parsedType === ZodParsedType.undefined
) {
const { ctx } = this._processInputParams(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nonNullable,
received: ctx.parsedType,
});
return INVALID;
}
return this._def.innerType._parse(input);
}

unwrap() {
return this._def.innerType;
}

static create = <T extends ZodTypeAny>(
type: T,
params?: RawCreateParams
): ZodNonNullable<T> => {
return new ZodNonNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNonNullable,
...processCreateParams(params),
}) as any;
};
}

///////////////////////////////////////////
///////////////////////////////////////////
////////// //////////
Expand Down Expand Up @@ -4927,6 +4983,7 @@ export enum ZodFirstPartyTypeKind {
ZodEffects = "ZodEffects",
ZodNativeEnum = "ZodNativeEnum",
ZodOptional = "ZodOptional",
ZodNonNullable = "ZodNonNullable",
ZodNullable = "ZodNullable",
ZodDefault = "ZodDefault",
ZodCatch = "ZodCatch",
Expand Down Expand Up @@ -4965,6 +5022,7 @@ export type ZodFirstPartySchemaTypes =
| ZodNativeEnum<any>
| ZodOptional<any>
| ZodNullable<any>
| ZodNonNullable<any>
| ZodDefault<any>
| ZodCatch<any>
| ZodPromise<any>
Expand Down Expand Up @@ -5015,6 +5073,7 @@ const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const nonNullableType = ZodNonNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = () => stringType().optional();
Expand Down Expand Up @@ -5055,6 +5114,7 @@ export {
nanType as nan,
nativeEnumType as nativeEnum,
neverType as never,
nonNullableType as nonNullable,
nullType as null,
nullableType as nullable,
numberType as number,
Expand Down
Loading