or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-schemas.mdcoercion.mdcollections.mderrors.mdindex.mdiso-datetime.mdjson-schema.mdlocales.mdnumber-formats.mdparsing.mdprimitives.mdrefinements.mdstring-formats.mdtransformations.mdunions-intersections.mdutilities.mdwrappers.md

index.mddocs/

0

# Zod

1

2

TypeScript-first schema validation library with static type inference and runtime validation.

3

4

## Package Information

5

6

- **Package**: `zod` (npm)

7

- **Installation**: `npm install zod`

8

- **Import**: `import { z } from "zod"`

9

- **Docs**: https://zod.dev/api

10

11

## Quick Reference

12

13

```typescript

14

// Basic schema definition and usage

15

import { z } from "zod";

16

17

// Define schema

18

const UserSchema = z.object({

19

name: z.string(),

20

email: z.email(),

21

age: z.number().positive(),

22

});

23

24

// Parse (throws on error)

25

const user = UserSchema.parse(data);

26

27

// Safe parse (returns result object)

28

const result = UserSchema.safeParse(data);

29

if (result.success) {

30

console.log(result.data);

31

} else {

32

console.log(result.error);

33

}

34

35

// Type inference

36

type User = z.infer<typeof UserSchema>;

37

```

38

39

## Common Patterns

40

41

### Schema Creation

42

```typescript

43

// Primitives

44

z.string()

45

z.number()

46

z.boolean()

47

z.date()

48

z.bigint()

49

z.symbol()

50

51

// String formats

52

z.email()

53

z.url()

54

z.uuid()

55

z.ipv4() / z.ipv6()

56

57

// Collections

58

z.array(z.string())

59

z.object({ key: z.string() })

60

z.tuple([z.string(), z.number()])

61

z.record(z.string(), z.number())

62

z.enum(["a", "b", "c"])

63

64

// Modifiers

65

z.string().optional()

66

z.string().nullable()

67

z.string().default("value")

68

z.union([z.string(), z.number()])

69

```

70

71

### Validation Patterns

72

```typescript

73

// String validation

74

z.string().min(3).max(20).regex(/^[a-z]+$/)

75

z.string().email().max(255)

76

z.string().trim().toLowerCase()

77

78

// Number validation

79

z.number().int().positive().min(0).max(100)

80

z.number().multipleOf(5)

81

82

// Object validation

83

z.object({

84

name: z.string(),

85

age: z.number()

86

}).strict() // or .passthrough() or .strip()

87

88

// Custom validation

89

z.string().refine((val) => val.length > 0, "Required")

90

z.object({...}).superRefine((data, ctx) => {

91

ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Error" });

92

})

93

94

// Transformations

95

z.string().transform((val) => val.toUpperCase())

96

z.pipe(z.string(), z.number())

97

```

98

99

### Error Handling

100

```typescript

101

// Try-catch

102

try {

103

const data = schema.parse(input);

104

} catch (error) {

105

if (error instanceof z.ZodError) {

106

console.log(error.issues);

107

}

108

}

109

110

// Safe parse (preferred)

111

const result = schema.safeParse(input);

112

if (!result.success) {

113

console.log(result.error.format()); // Tree structure

114

console.log(result.error.flatten()); // Flat structure

115

}

116

117

// Async validation

118

await schema.parseAsync(data);

119

await schema.safeParseAsync(data);

120

```

121

122

## Core Concepts

123

124

**Schemas** - Immutable validation objects with type inference

125

**Parsing** - Validation with throwing (`parse`) or safe (`safeParse`) methods

126

**Type Inference** - `z.infer<typeof Schema>` extracts TypeScript types

127

**Chainable API** - Methods return new schema instances

128

**Transformations** - Type-safe data transformation pipelines

129

130

## Feature Documentation

131

132

### Type Schemas

133

134

- **[Primitives](./primitives.md)** - string, number, boolean, date, bigint, symbol, null, undefined, any, unknown, never

135

- **[String Formats](./string-formats.md)** - email, url, uuid, ip addresses, JWT, base64, IDs (cuid, ulid, nanoid)

136

- **[Number Formats](./number-formats.md)** - int, int32, uint32, float32, float64, int64, uint64

137

- **[Collections](./collections.md)** - array, object, tuple, record, map, set, enum, literal

138

- **[ISO DateTime](./iso-datetime.md)** - datetime, date, time, duration validation

139

140

### Schema Operations

141

142

- **[Parsing & Validation](./parsing.md)** - parse, safeParse, parseAsync, safeParseAsync methods

143

- **[Refinements](./refinements.md)** - refine, superRefine, custom validation logic

144

- **[Transformations](./transformations.md)** - transform, pipe, preprocess, codec

145

- **[Wrappers](./wrappers.md)** - optional, nullable, default, catch modifiers

146

- **[Unions & Intersections](./unions-intersections.md)** - union, discriminatedUnion, intersection

147

148

### Advanced Features

149

150

- **[Advanced Schemas](./advanced-schemas.md)** - function, promise, lazy, custom, instanceof, file

151

- **[Type Coercion](./coercion.md)** - z.coerce for automatic type conversion

152

- **[Error Handling](./errors.md)** - ZodError, issue types, formatting utilities

153

- **[Utilities](./utilities.md)** - Type inference, schema cloning, configuration

154

- **[Internationalization](./locales.md)** - 44+ languages support

155

- **[JSON Schema](./json-schema.md)** - Convert Zod schemas to JSON Schema

156

157

## API Surface

158

159

All functionality is accessed through the `z` namespace object. Key methods:

160

161

```typescript { .api }

162

// Primitives

163

z.string() z.number() z.boolean() z.date() z.bigint() z.symbol()

164

z.undefined() z.null() z.any() z.unknown() z.never() z.void() z.nan()

165

166

// String formats

167

z.email() z.url() z.uuid() z.ipv4() z.ipv6() z.jwt()

168

z.cuid() z.ulid() z.nanoid() z.base64()

169

170

// Collections

171

z.array(T) z.object({...}) z.tuple([...]) z.record(K, V)

172

z.map(K, V) z.set(T) z.enum([...]) z.literal(value)

173

174

// Composition

175

z.union([...]) z.discriminatedUnion(key, [...]) z.intersection(A, B)

176

z.optional(T) z.nullable(T) z.default(T, val)

177

178

// Advanced

179

z.function() z.promise(T) z.lazy(() => T) z.custom()

180

z.instanceof(Class) z.file()

181

182

// Operations

183

schema.parse(data) // Throws on error

184

schema.safeParse(data) // Returns result object

185

schema.parseAsync(data) // Async parse

186

schema.safeParseAsync(data) // Async safe parse

187

188

// Refinements & Transformations

189

schema.refine(fn, msg) // Add validation

190

schema.superRefine((val, ctx)) // Advanced validation

191

schema.transform(fn) // Transform data

192

z.pipe(A, B) // Pipeline schemas

193

194

// Type inference

195

type T = z.infer<typeof schema>

196

type In = z.input<typeof schema>

197

type Out = z.output<typeof schema>

198

```

199

200

## Types

201

202

```typescript { .api }

203

// Base type for all Zod schemas

204

interface ZodType<Output = any, Input = any> {

205

_output: Output;

206

_input: Input;

207

_def: ZodTypeDef;

208

209

parse(data: unknown, params?: ParseContext): Output;

210

safeParse(data: unknown, params?: ParseContext): SafeParseResult<Output>;

211

parseAsync(data: unknown, params?: ParseContext): Promise<Output>;

212

safeParseAsync(data: unknown, params?: ParseContext): Promise<SafeParseResult<Output>>;

213

refine(check: (val: Output) => boolean, msg?: string): this;

214

superRefine(check: (val: Output, ctx: RefinementCtx) => void): this;

215

transform<T>(fn: (val: Output) => T): ZodEffects<this, T>;

216

}

217

218

type ZodTypeAny = ZodType<any, any>;

219

220

type SafeParseResult<T> =

221

| { success: true; data: T }

222

| { success: false; error: ZodError };

223

224

// Primitive type

225

type Primitive = string | number | bigint | boolean | null | undefined;

226

227

// Shape for object schemas

228

type ZodRawShape = { [k: string]: ZodTypeAny };

229

230

// Type inference helpers

231

type infer<T extends ZodType> = T["_output"];

232

type input<T extends ZodType> = T["_input"];

233

type output<T extends ZodType> = T["_output"];

234

235

// Error map for custom error messages

236

type ZodErrorMap = (issue: ZodIssueOptionalMessage, ctx: ErrorMapCtx) => { message: string };

237

238

// Parse context for customizing validation behavior

239

interface ParseContext {

240

error?: ZodErrorMap;

241

reportInput?: boolean;

242

jitless?: boolean;

243

}

244

245

interface RefinementCtx {

246

addIssue(issue: IssueData): void;

247

path: (string | number)[];

248

}

249

```

250