Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
Maintainers
1
Versions
361
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zod - npm Package Compare versions

Comparing version 1.7.0 to 1.7.1

2

lib/src/index.d.ts

@@ -50,3 +50,3 @@ import { ZodString, ZodStringDef } from './types/string';

export { stringType as string, numberType as number, bigIntType as bigint, booleanType as boolean, dateType as date, undefinedType as undefined, nullType as null, anyType as any, unknownType as unknown, arrayType as array, objectType as object, unionType as union, intersectionType as intersection, tupleType as tuple, recordType as record, functionType as function, lazyType as lazy, literalType as literal, enumType as enum, promiseType as promise, ostring, onumber, oboolean, };
export { ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodRecord, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodPromise, ZodType, ZodTypeAny, ZodDef, ZodError, };
export { ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodRecord, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodPromise, ZodType, ZodType as Schema, ZodTypeAny, ZodDef, ZodError, };
export { TypeOf, TypeOf as infer };

@@ -46,2 +46,3 @@ "use strict";

exports.ZodType = base_1.ZodType;
exports.Schema = base_1.ZodType;
var ZodError_1 = require("./ZodError");

@@ -48,0 +49,0 @@ exports.ZodError = ZodError_1.ZodError;

@@ -348,5 +348,3 @@ "use strict";

return obj;
// assertNever();
// return obj;
}; };
//# sourceMappingURL=parser.js.map
"use strict";
// import * as z from '.';
// const STATUSES = ['Assigned', 'In Progress', 'On Location', 'Succeeded', 'Failed'] as const;
// const literals = STATUSES.map(z.literal);
// // const StatusSchema = z.union(STATUSES.map(z.literal));
// const StatusSchema2 = z.enum(STATUSES);
// const StatusSchema3 = z.enum(['Assigned', 'In Progress', 'On Location', 'Succeeded', 'Failed']);
// const asdf = StatusSchema3.OptionsArray;
// const asdf = Object.values(StatusSchema3.Values);
// StatusSchema3._def.values;
// StatusSchema3.Values;
// type StatusSchema2 = z.infer<typeof StatusSchema2>
// const fishTypes = ['Salmon', 'Tuna', 'Trout'] as const;
// const FishEnum = z.enum(fishTypes);
//# sourceMappingURL=playground.js.map

@@ -19,5 +19,7 @@ import * as z from './base';

toJSON: () => ZodEnumDef<T>;
readonly OptionsList: T;
readonly Values: Values<T>;
readonly Enum: Values<T>;
static create: <U extends string, T_1 extends [U, ...U[]]>(values: T_1) => ZodEnum<T_1>;
}
export {};

@@ -36,2 +36,9 @@ "use strict";

}
Object.defineProperty(ZodEnum.prototype, "OptionsList", {
get: function () {
return this._def.values;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ZodEnum.prototype, "Values", {

@@ -49,2 +56,14 @@ get: function () {

});
Object.defineProperty(ZodEnum.prototype, "Enum", {
get: function () {
var enumValues = {};
for (var _i = 0, _a = this._def.values; _i < _a.length; _i++) {
var val = _a[_i];
enumValues[val] = val;
}
return enumValues;
},
enumerable: true,
configurable: true
});
ZodEnum.create = function (values) {

@@ -51,0 +70,0 @@ return new ZodEnum({

@@ -37,2 +37,3 @@ import * as z from './base';

augment: <Augmentation extends z.ZodRawShape>(augmentation: Augmentation) => ZodObject<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k in keyof Augmentation]: Augmentation[k]; }, Params>;
extend: <Augmentation extends z.ZodRawShape>(augmentation: Augmentation) => ZodObject<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k in keyof Augmentation]: Augmentation[k]; }, Params>;
/**

@@ -39,0 +40,0 @@ * Prior to zod@1.0.12 there was a bug in the

@@ -74,2 +74,3 @@ "use strict";

_this.augment = AugmentFactory(_this._def);
_this.extend = AugmentFactory(_this._def);
// augment = <Augmentation extends z.ZodRawShape>(

@@ -76,0 +77,0 @@ // augmentation: Augmentation,

{
"name": "zod",
"version": "1.7.0",
"version": "1.7.1",
"description": "TypeScript-first schema declaration and validation library with static type inference",

@@ -36,9 +36,2 @@ "main": "./lib/src/index.js",

],
"include": [
"src"
],
"exclude": [
"node_modules",
"**/__tests__/*"
],
"scripts": {

@@ -52,3 +45,3 @@ "clean": "rm -rf lib/*",

"badge": "make-coverage-badge --output-path ./coverage.svg",
"prepare": "npm run build",
"prepublishOnly": "npm run build",
"play": "nodemon -e ts -w . -x ts-node src/playground.ts"

@@ -67,2 +60,2 @@ },

}
}
}

@@ -28,29 +28,31 @@ <p align="center">

- [Installation](#installation)
- [Usage](#usage)
- [Primitives](#primitives)
- [Literals](#literals)
- [Parsing](#parsing)
- [Type inference](#type-inference)
- [Custom validation](#custom-validation)
- [Objects](#objects)
- [.nonstrict](#unknown-keys)
- [.merge](#merging)
- [.augment](#augmentation)
- [.pick/.omit](#masking)
- [.partial/.deepPartial](#partials)
- [Records](#records)
- [Arrays](#arrays)
- [.nonempty](#non-empty-lists)
- [Unions](#unions)
- [.optional](#optional-types)
- [.nullable](#nullable-types)
- [.enum](#enums)
- [Intersections](#intersections)
- [Tuples](#tuples)
- [Recursive types](#recursive-types)
- [JSON type](#json-type)
- [Cyclical data](#cyclical-objects)
- [Promises](#promises)
- [Function schemas](#function-schemas)
- [Errors](#errors)
<!-- - [Usage](#usage) -->
- [Primitives](#primitives)
- [Literals](#literals)
- [Parsing](#parsing)
- [Type inference](#type-inference)
- [Custom validation](#custom-validation)
- [Strings](#strings)
- [Numbers](#numbers)
- [Objects](#objects)
- [.nonstrict](#unknown-keys)
- [.merge](#merging)
- [.augment](#augmentation)
- [.pick/.omit](#masking)
- [.partial/.deepPartial](#partials)
- [Records](#records)
- [Arrays](#arrays)
- [.nonempty](#non-empty-lists)
- [Unions](#unions)
- [.optional](#optional-types)
- [.nullable](#nullable-types)
- [.enum](#enums)
- [Intersections](#intersections)
- [Tuples](#tuples)
- [Recursive types](#recursive-types)
- [JSON type](#json-type)
- [Cyclical data](#cyclical-objects)
- [Promises](#promises)
- [Function schemas](#function-schemas)
- [Errors](#errors)
- [Comparison](#comparison)

@@ -251,3 +253,3 @@ - [Joi](#joi)

z.number().int(5); // value must be an integer
z.number().int(); // value must be an integer

@@ -326,3 +328,3 @@ z.number().positive(); // > 0

`.merge` is just syntactic sugar over the more generic `z.intersection` which is documented below.
<!-- `.merge` is just syntactic sugar over the more generic `z.intersection` which is documented below. -->

@@ -358,3 +360,3 @@ > IMPORTANT: the schema returned by `.merge` is the _intersection_ of the two schemas. The schema passed into `.merge` does not "overwrite" properties of the original schema. To demonstrate:

⚠️ You can use `.augment` to overwrite fields! Be careful with this power!
> ⚠️ You can use `.augment` to overwrite fields! Be careful with this power!

@@ -372,3 +374,3 @@ ```ts

Object masking is one of Zod's killer features. It lets you create slight variations of your object schemas easily and succinctly.
Object masking is one of Zod's killer features. It lets you create slight variations of your object schemas easily and succinctly. Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a "masked" version of the schema.

@@ -383,4 +385,2 @@ ```ts

Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a "masked" version of the schema.
To only keep certain keys, use `.pick`.

@@ -391,3 +391,4 @@

type JustTheName = z.infer<typeof JustTheName>; // => { name: string }
type JustTheName = z.infer<typeof JustTheName>;
// => { name: string }
```

@@ -400,3 +401,4 @@

type NoIDRecipe = z.infer<typeof NoIDRecipe>; // => { name: string, ingredients: string[] }
type NoIDRecipe = z.infer<typeof NoIDRecipe>;
// => { name: string, ingredients: string[] }
```

@@ -406,3 +408,3 @@

This is a vital feature for implementing typesafe backend logic, yet as far as I know, no other validation library (yup, Joi, io-ts, runtypes, class-validator, ow...) offers similar functionality as of this writing (April 2020). This is one of the must-have features that inspired the creation of Zod.
> This is a vital feature for implementing typesafe backend logic, yet as far as I know, no other validation library (yup, Joi, io-ts, runtypes, class-validator, ow...) offers similar functionality as of this writing (April 2020). This is one of the must-have features that inspired the creation of Zod.

@@ -465,9 +467,14 @@ #### Partials

Important limitation: deep partials only work as expected in hierarchies of object schemas. It also can't be used on recursive schemas currently, since creating a recursive schema requires casting to the generic `ZodType` type (which doesn't include all the methods of the `ZodObject` class). Currently an improved version of Zod is under development that will have better support for recursive schemas.
> Important limitation: deep partials only work as expected in hierarchies of object schemas. It also can't be used on recursive schemas currently, since creating a recursive schema requires casting to the generic `ZodType` type (which doesn't include all the methods of the `ZodObject` class). Currently an improved version of Zod is under development that will have better support for recursive schemas.
#### Unknown keys
IMPORTANT: By default, Zod object schemas _do not_ allow unknown keys.
By default, Zod object schemas _do not_ allow unknown keys!
```ts
const dogSchema = z.object({
name: z.string(),
neutered: z.boolean(),
});
dogSchema.parse({

@@ -483,2 +490,4 @@ name: 'Spot',

```ts
type Dog = z.infer<typeof dogSchema>;
const spot: Dog = {

@@ -520,11 +529,19 @@ name: 'Spot',

Records are similar to object schemas, but don't enforce a type restriction on the keys. For instance:
Record schemas are used to validate types such as this:
```ts
const objectSchema = z.object({ name: z.string() });
type NumberCache = { [k: string]: number };
```
`objectSchema` only accepts objects with single key: `name`. You could use `.nonstrict()` to create a schema that accepts unknown keys, but that schema doesn't enforce a type on the _values_ associated with those unknown keys.
If you want to validate that all the _values_ of an object match some schema, without caring about the keys, you should use a Record.
```ts
<!-- Records are similar to object schemas, but don't enforce a type restriction on the keys. For instance: -->
<!-- ```ts
const objectSchema = z.object({ name: z.string() });
``` -->
<!-- `objectSchema` only accepts objects with single key: `name`. You could use `.nonstrict()` to create a schema that accepts unknown keys, but that schema doesn't enforce a type on the _values_ associated with those unknown keys. -->
<!-- ```ts
const nonstrict = objectSchema.nonstrict();

@@ -536,5 +553,5 @@ type nonstrict = z.infer<typeof nonstrict>;

parsed.bar; // no type information
```
``` -->
But what if you want an object that enforces a schema on all of the values it contains? That's when you would use a record.
<!-- But what if you want an object that enforces a schema on all of the values it contains? That's when you would use a record. -->

@@ -547,4 +564,5 @@ ```ts

const UserStore = z.record(User);
type UserStore = z.infer<typeof UserStore>;
// => { [k: string]: { name: string } }
// => { [k: string]: User }
```

@@ -576,3 +594,3 @@

You may have expected `z.record()` to accept two arguments, one for the keys and one for the values. After all, TypeScript's built-in Record type does (`Record<KeyType, ValueType>`). Otherwise, how do you represent the TypeScript type `Record<number, any>` in Zod?
You may have expected `z.record()` to accept two arguments, one for the keys and one for the values. After all, TypeScript's built-in Record type does: `Record<KeyType, ValueType>`. Otherwise, how do you represent the TypeScript type `Record<number, any>` in Zod?

@@ -592,4 +610,6 @@ As it turns out, TypeScript's behavior surrounding `[k: number]` is a little unintuitive:

As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.
As you can see, JavaScript automatically casts all object keys to strings under the hood.
Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.
## Arrays

@@ -636,3 +656,3 @@

#### Optional types
### Optional types

@@ -659,3 +679,3 @@ Unions are the basis for defining optional schemas. An "optional string" is just the union of `string` and `undefined`.

#### Nullable types
### Nullable types

@@ -695,5 +715,5 @@ Similarly, you can create nullable types like so:

#### Enums
### Enums
You can combine unions and string literals to create an enum schemas.
An enum is just a union of string literals, so you can "build your own enum" like this:

@@ -707,11 +727,32 @@ ```ts

You can also use the built-in `z.enum()` function, like so:
But for convenience Zod provides a built-in `z.enum()` function, like so:
```ts
const FishEnum = z.enum(['Salmon', 'Tuna', 'Trout']);
type FishEnum = z.infer<typeof FishEnum>;
// 'Salmon' | 'Tuna' | 'Trout'
```
// if you use `z.enum([ ... ])`
// you can also autocomplete enum values
// with the computed `.Values` property
> You need to either need to pass the literal array directly into z.enum:
>
> ```ts
> const FishEnum = z.enum(['Salmon', 'Tuna', 'Trout']);
> ```
>
> or use `as const` (introduced in TypeScript 3.4):
>
> ```ts
> const fishTypes = ['Salmon', 'Tuna', 'Trout'] as const;
> const FishEnum = z.enum(fishTypes);
> ```
>
> otherwise type inference won't work properly.
#### Autocompletion
You can get autocompletion of enum values with the `.Values` property of an enum schema:
```ts
FishEnum.Values.Salmon; // => autocompletes
FishEnum.Values;

@@ -805,4 +846,6 @@ /*

Unfortunately this code is a bit duplicative, since you're declaring the types twice: once in the interface and again in the Zod definition. If your schema has lots of primitive fields, there's a way of reducing the amount of duplication:
Unfortunately this code is a bit duplicative, since you're declaring the types twice: once in the interface and again in the Zod definition.
If your schema has lots of primitive fields, there's a way of reducing the amount of duplication:
```ts

@@ -896,3 +939,3 @@ // define all the non-recursive stuff here

When "parsing" a promise, Zod checks that the passed value is an object with `.then` and `.catch` methods - that's it. So you should be able to pass non-native Promises (Bluebird, etc) into `z.promise(...).parse` with no trouble. One gotcha: the return type of the parse function will be a _native_ `Promise`, so if you have downstream logic that uses non-standard Promise methods, this won't work.
When "parsing" a promise, Zod checks that the passed value is an object with `.then` and `.catch` methods — that's it. So you should be able to pass non-native Promises (Bluebird, etc) into `z.promise(...).parse` with no trouble. One gotcha: the return type of the parse function will be a _native_ `Promise`, so if you have downstream logic that uses non-standard Promise methods, this won't work.

@@ -960,3 +1003,3 @@ ## Function schemas

This is particularly useful for defining HTTP or RPC endpoints that accept complex payloads that require validation. Moreover, you can define your endpoints once with Zod and share the code with both your client and server code to achieve end-to-end type safety.
> This is particularly useful for defining HTTP or RPC endpoints that accept complex payloads that require validation. Moreover, you can define your endpoints once with Zod and share the code with both your client and server code to achieve end-to-end type safety.

@@ -963,0 +1006,0 @@ ```ts

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc