Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
0
Maintainers
1
Versions
359
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.8 to 1.0.9

2

lib/index.d.ts

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

declare const lazyType: <T extends ZodAny>(getter: () => T) => ZodLazy<T>;
declare const literalType: <T extends string | number | boolean>(value: T) => ZodLiteral<T>;
declare const literalType: <T extends string | number | boolean | null | undefined>(value: T) => ZodLiteral<T>;
declare const enumType: <T extends [ZodLiteral<string>, ...ZodLiteral<string>[]]>(values: T) => ZodEnum<T>;

@@ -32,0 +32,0 @@ declare const ostring: () => ZodUnion<[ZodString, ZodUndefined]>;

"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var z = __importStar(require("."));
var MyEnum = z.enum([z.literal('Hello'), z.literal('There'), z.literal('Bobby')]);
MyEnum.parse('Bobby');
// import * as z from '.';
// const und = z.literal(undefined);
// const MyEnum = z.enum([z.literal('Hello'), z.literal('There'), z.literal('Bobby')]);
// MyEnum.parse('Bobby');
// type MyEnum = z.Infer<typeof MyEnum>;
// const CellText = z.object({
// kind: z.literal('text'),
// body: z.string(),
// });
// const CellCode = z.object({
// kind: z.literal('code'),
// code: z.string(),
// });
// const Schema = z.array(
// z.object({
// category: z.string(),
// cells: z.array(z.union([CellText, CellCode])).nonempty(),
// }),
// );
// // const y: ['asdf', 'qwer'] = ['asdf', 'qwer'];
// type U = ['asdf', 'qwer']
// type Tail<Tuple extends any[]> = ((...args: Tuple) => any) extends (_: any, ..._1: infer Rest) => any
// ? Rest extends any[] ? Rest : never
// : never;
// export type ArrayKeys = keyof any[];
// export type Indices<T> = Exclude<keyof T, ArrayKeys>;
// type UM<T extends string[]> = {[k in Indices<T>]: T[k] extends string ? z.ZodLiteral<T[k]> : never};
// type UMU = UM<U>
// type p = UMU[0]
// type Ad = Tail<string[]>
// type Mapper<T extends string[]> = {
// empty: T,
// single: T,
// many: [T[0], ...ForceArray<Mapper<T>>],
// never: never
// }[T extends [] ? 'empty' : T extends [any] ? 'single' : T extends any[] ? 'many' : 'never'];
// type ForceArray<T extends any[]> = T extends (infer U) ? U extends any[] ? U : never : never;
// type MapRest<T extends string[]> = { 0: Mapper<Tail<T>> extends any[] ? Mapper<Tail<T>> : never, 1: never }[true ? 0 : 1]
// type MU = MapRest<["wer", "asdf"]>
// // if (!Schema.is(y)) {
// // y[0].cells[0].kind; // => "text" | "code"
// // throw new Error("adsf")
// // }
//# sourceMappingURL=playground.js.map

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

import { ZodUnion } from './union';
declare type LiteralValue = string | number | boolean;
declare type LiteralValue = string | number | boolean | undefined | null;
export interface ZodLiteralDef<T extends LiteralValue = LiteralValue> extends z.ZodTypeDef {

@@ -15,4 +15,4 @@ t: z.ZodTypes.literal;

toJSON: () => ZodLiteralDef<T>;
static create: <T_1 extends string | number | boolean>(value: T_1) => ZodLiteral<T_1>;
static create: <T_1 extends LiteralValue>(value: T_1) => ZodLiteral<T_1>;
}
export {};
{
"name": "zod",
"version": "1.0.8",
"version": "1.0.9",
"description": "Typescript-first schema declaration and validation library with static type inference",

@@ -5,0 +5,0 @@ "main": "./lib/index.js",

@@ -39,8 +39,15 @@ # Zod

Zod is a validation library designed for optimal developer experience.
Zod is a validation library designed for optimal developer experience. It's a Typescript-first schema declaration library with rigorous (and correct!) inferred types, incredible developer experience, and a few killer features missing from the existing libraries.
- It takes advantage of Typescript generic inference to statically infer the types of your schemas, eliminating the need to define static types and runtime validators separately.
- Eliminates the need to keep static types and runtime validators in sync by hand
- It has a composable, declarative API that makes it easy to define complex types concisely.
- Schemas are immutable. All methods return a new schema instance.
Zod was also designed with some core principles designed to make all declarations as non-magical and developer-friendly as possible:
- All fields are required unless explicitly marked as optional (just like Typescript!)
- Schemas are immutable; methods (i.e. `.optional()` return a new instance.
- Zod schemas operate on a ["Parse, don't validate!"](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) basis!
## Primitives

@@ -58,6 +65,15 @@

## Parsing
## Literals
```ts
// every ZodType instance has a .parse() method
const tuna = z.literal('tuna'); // => ZodType<'tuna'>
const twelve = z.literal(12); // => ZodType<12>
const tru = z.boolean(true); // => ZodType<true>
```
## Parsing and validation
Given a Zod schema, you can call its `.parse(data)` method to check `data` is valid. If it is, `data` is returned (with full type information!). Otherwise, an error is thrown.
```ts
const stringSchema = z.string();

@@ -68,2 +84,28 @@ stringSchema.parse('fish'); // => "fish"

You can also use a Zod schema as a type guard using the schema's `.is()` method, like so:
```ts
const stringSchema = z.string();
const blob: any = 'Albuquerque';
if (stringSchema.check(blob)) {
// blob is now of type `string`
// within this if statement
}
```
The same method can be used to check a _lack_ of
```ts
const stringSchema = z.string();
const process = (blob: any) => {
if (!stringSchema.is(blob)) {
throw new Error('Not a string');
}
// blob is now of type `string`
// underneath the if statement
};
```
## Type inference

@@ -132,4 +174,2 @@

Including Nullable and Optional types.
Zod includes a built-in `z.union` method for composing "OR" types.

@@ -144,9 +184,9 @@

Unions are the basis for defining nullable and optional values.
### Optional types
Unions are the basis for defining optional schemas. An "optional string" is just the union of `string` and `undefined`.
```ts
/* Optional Types */
const A = z.union([z.string(), z.undefined()]);
// "optional string" === the union of string and undefined
const A = z.union([z.string(), z.undefined()]);
A.parse(undefined); // => passes, returns undefined

@@ -156,3 +196,3 @@ type A = z.TypeOf<typeof A>; // string | undefined

There is also a shorthand way to make a schema "optional":
Zod provides a shorthand way to make any schema optional:

@@ -168,8 +208,13 @@ ```ts

### Nullable types
Similarly, you can create nullable types like so:
```ts
/* Nullable Types */
const D = z.union([z.string(), z.null()]);
```
Or you can use the shorthand `.nullable()`:
```ts
const E = z.string().nullable(); // equivalent to D

@@ -179,3 +224,3 @@ type E = z.TypeOf<typeof D>; // string | null

You can create unions of any two schemas.
You can create unions of any two or more schemas.

@@ -186,7 +231,9 @@ ```ts

const F = z
.union([z.string(), z.number()])
.union([z.string(), z.number(), z.boolean()])
.optional()
.nullable();
F.parse('tuna'); // => tuna
F.parse(42); // => 42
F.parse(true); // => true
F.parse(undefined); // => undefined

@@ -196,5 +243,34 @@ F.parse(null); // => null

type F = z.TypeOf<typeof F>; // string | number | undefined | null;
type F = z.TypeOf<typeof F>; // string | number | boolean | undefined | null;
```
### Enums
You can combine unions and string literals to create an enum schemas.
```ts
const FishEnum = t.union([t.literal('Salmon'), t.literal('Tuna'), t.literal('Trout')]);
FishEnum.parse('Salmon'); // => "Salmon"
FishEnum.parse('Flounder'); // => throws
```
You can also use the built-in `z.enum()` function, like so:
```ts
const FishEnum = t.enum([t.literal('Salmon'), t.literal('Tuna'), t.literal('Trout')]);
// you can autocomplete values
// with the `.Values` variable
FishEnum.Values.Salmon; // => autocompletes
FishEnum.Values;
/*
{
Salmon: "Salmon",
Tuna: "Tuna",
Trout: "Trout",
}
*/
```
## Intersections

@@ -283,3 +359,3 @@

subcategories: z.array(Category),
})
}),
);

@@ -317,3 +393,3 @@

name: string(),
})
}),
);

@@ -352,3 +428,3 @@

limit: 20,
}
},
);

@@ -355,0 +431,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc