{"_id":"@arilotter/myzod","name":"@arilotter/myzod","dist-tags":{"latest":"1.11.0"},"versions":{"1.11.0":{"name":"@arilotter/myzod","version":"1.11.0","description":"Schema Validation with typescript type inference.","main":"./libs/index.js","types":"./libs/index.d.ts","scripts":{"test":"nyc mocha \"test/**/*test.ts\"","build":"rm -rf ./libs && tsc","pub":"npm t && npm run build && npm publish","bench":"find test -path '*.benchmark.ts' | xargs benchmonkey","prettier":"prettier --write '**/*.ts'"},"keywords":["typescript","schema","validation","type","inference","zod"],"repository":{"type":"git","url":"git+https://github.com/davidmdm/myzod.git"},"author":"","license":"MIT","devDependencies":{"@types/mocha":"^10.0.1","@types/node":"^18.14.2","benchmonkey":"^0.0.8","mocha":"^10.2.0","nyc":"^15.1.0","prettier":"^2.8.4","ts-node":"^10.9.1","typescript":"^4.9.5"},"nyc":{"include":["src/**/*.ts"],"extension":[".ts"],"require":["ts-node/register"],"reporter":["html","text"],"sourceMap":true,"instrument":true},"mocha":{"require":["ts-node/register"],"timeout":5000,"exit":true},"benchmonkey":{"require":["ts-node/register"]},"_id":"@arilotter/myzod@1.11.0","gitHead":"4bfca330bfb79e535696dc2ee45a20f3fc846045","bugs":{"url":"https://github.com/davidmdm/myzod/issues"},"homepage":"https://github.com/davidmdm/myzod#readme","_nodeVersion":"20.6.1","_npmVersion":"9.8.1","dist":{"integrity":"sha512-qP0JWduwTunIoKbR3xe65YNZhrRso3WQjVlrXSPIl7tCMB6EXmCS3RL0UnBwhcvh0J6fBmSBAZ7Fl4YMXvqoOw==","shasum":"c02821db986f6663f66462c946b7a7305e38e22e","tarball":"https://registry.npmjs.org/@arilotter/myzod/-/myzod-1.11.0.tgz","fileCount":8,"unpackedSize":111969,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIE72gFbEiqJiUm35iW9aLmhGr7qR8gioEIk+JpjzOjRtAiB2OujSZiq9rEYsEeQC2Bt3JDX3y6Lk4WGb2K1w33UDgQ=="}]},"_npmUser":{"name":"arilotter","email":"arilotter@gmail.com"},"directories":{},"maintainers":[{"name":"arilotter","email":"arilotter@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/myzod_1.11.0_1694634667444_0.8806112945003497"},"_hasShrinkwrap":false}},"time":{"created":"2023-09-13T19:51:07.349Z","1.11.0":"2023-09-13T19:51:07.640Z","modified":"2023-09-13T19:51:07.922Z"},"maintainers":[{"name":"arilotter","email":"arilotter@gmail.com"}],"description":"Schema Validation with typescript type inference.","homepage":"https://github.com/davidmdm/myzod#readme","keywords":["typescript","schema","validation","type","inference","zod"],"repository":{"type":"git","url":"git+https://github.com/davidmdm/myzod.git"},"bugs":{"url":"https://github.com/davidmdm/myzod/issues"},"license":"MIT","readme":"# myzod\n\nSchema Validation with typescript type inference.\n\n### Acknowledgements\n\nMajor Shout-out to [zod](https://www.npmjs.com/package/zod) for the inspiration.\n\n### Description\n\nMyzod tries to emulate the typescript type system as much as possible and is even in some ways a little stricter. The goal is that writing a schema feels the same as defining a typescript type, with equivalent & and | operators, and well known Generic types like Record, Pick and Omit. On top of that myzod aims to offer validation within the schemas for such things as number ranges, string patterns and lengths to help enforce business logic.\n\nThe resulting package has a similar api to `zod` with a little bit of inspiration from [joi](https://www.npmjs.com/package/@hapi/joi).\n\nThe goal is to write schemas from which the _type_ of a successfully parsed value can be inferred. With myzod typescript types and validation logic no longer need to be maintained separately.\n\n### Performance\n\nWhen parsing equivalent simple object (with nesting) schemas for myzod, zod and joi, on my machine Linux Ubuntu 18.04 running NodeJS 13.X, the results are as such:\n\nobjects parsed per second:\n\n- `zod`: 51861\n- `joi`: 194325\n- `myzod`: 1288659\n\nmyzod vs zod: ~25 X Speedup\n\nmyzod vs joi: ~6 X Speedup\n\n### Installation\n\n```\nnpm install --save myzod\n```\n\n### Usage\n\nMyzod is used by creating a schema, extracting the type by inferring it, and finally by parsing javascript values.\n\n```typescript\nimport myzod, { Infer } from 'myzod';\n\nconst personSchema = myzod.object({\n  id: myzod.number(),\n  name: myzod.string().pattern(/^[A-Z]/),\n  age: myzod.number().min(0),\n  birthdate: myzod.number().or(myzod.string()),\n  employed: myzod.boolean(),\n  friendIds: myzod.array(myzod.number()).nullable()\n});\n\ntype Person = Infer<typeof personSchema>;\n\nconst person: Person = personSchema.parse({ ... });\n```\n\n### Api Reference\n\nType Root\n\n- [Type<T>](#type)\n  - [parse](#typeparse)\n  - [try](#typetry)\n  - [and](#typeand)\n  - [or](#typeor)\n  - [optional](#typeoptional)\n  - [nullable](#typenullable)\n\nPrimitive Types\n\n- [string](#string)\n- [number](#number)\n- [bigint](#bigint)\n- [boolean](#boolean)\n- [undefined](#undefined)\n- [null](#null)\n- [literal](#literal)\n- [unknown](#unknown)\n\nReference Types\n\n- [object](#object)\n  - [pick/omit/partial](#object.pick/omit/partial)\n- [record](#record)\n- [array](#array)\n- [tuple](#tuple)\n- [enum](#enum)\n- [date](#date)\n\nLogical Types\n\n- [union](#union)\n- [intersection](#intersection)\n- [partial](#partial)\n- [pick](#pick)\n- [omit](#omit)\n\nRecursive Schemas\n\n- [lazy](#lazy)\n\n### Type.\n\nAll myzod schemas extend the generic myzod.Type class, and as such inherit these methods:\n\n#### Type.parse\n\nTakes an unknown value, and returns it typed if passed validation. Otherwise throws a myzod.ValidationError\n\n```typescript\nparse(value: unknown): T\n```\n\n#### Type.try\n\nTakes an unknown value and returns a result which will either be the parsed value or an instance of ValidationError.\nThis api is useful if you do not want to throw exceptions.\n\n```typescript\nconst result = schema.try(data);\nif (result instanceof myzod.ValidationError) {\n  // handle Error\n} else {\n  // result is of type: myzod.Infer<typeof schema>\n}\n```\n\n##### Type.and\n\nShorthand for creating intersection types of two schemas.\n\n```typescript\nconst nameSchema = myzod.object({ name: myzod.string() });\nconst ageSchema = myzod.object({ age: myzod.number() });\n\nconst personSchema = nameSchema.and(ageSchema); // Same as ageSchema.and(nameSchema);\n\ntype Person = Infer<typeof personSchema>; // => { name: string; age: number; }\n```\n\n##### Type.or\n\nShorthand for creating union types of two schemas.\n\n```typescript\nconst stringOrBoolSchema = myzod.string().or(myzod.boolean());\n\ntype StringOrUndefined = Infer<typeof stringOrBoolSchema>; // => string | boolean\n```\n\n##### Type.optional\n\nReturns a new schema which is a wrapped OptionalType of the current schema.\n\n```typescript\nconst optionalStringSchema = myzod.string().optional(); // => OptionalType<StringType>\n\ntype StringOrUndefined = Infer<typeof optionalStringSchema>; // => string | undefined\n```\n\nIt is possible to unwrap an optional schema via a call to require:\n\n```typescript\nconst optionalSchema = myzod.string().optional();\nconst schema = optionalSchema.require();\n```\n\n##### Type.nullable\n\nReturns a new schema which is a wrapped NullableType of the current schema.\n\n```typescript\nconst nullableStringSchema = myzod.string().nullable(); // => NullableType<StringType>\n\ntype StringOrUndefined = Infer<typeof nullableStringSchema>; // => string | null\n```\n\nIt is possible to unwrap an optional schema via a call to require:\n\n```typescript\nconst optionalSchema = myzod.string().nullable();\nconst schema = optionalSchema.require();\n```\n\n##### Type.map\n\nReturns a new generic schema to the mapped type. Useful for transforming validated input into a new type on parse.\n\n```typescript\nconst ObjectIDSchema = myzod\n  .string()\n  .withPredicate(ObjectId.isValid, 'must be an object ID')\n  .map(value => new ObjectId(value));\n\n// Infer<ObjectIDSchema> === ObjectId\n\nconst id = ObjectIDSchema.parse('507c7f79bcf86cd7994f6c0e');\nid instanceof ObjectId; // true\n\nconst id2 = ObjectIDSchema.parse('some string'); // Throws VaidationError with message \"must be an object ID\"'\n```\n\n#### String\n\noptions:\n\n- min `number` - min length of string\n- max `number` - max length of string\n- pattern `RegExp` - regular expression string must match\n- valid `string[]` - list of valid strings\n- predicate `Predicate<string>` - custom predicates to apply to string value\n\nmethods:\n\n- `min(value: number, errMsg?: string) => StringType`  \n   returns a new string schema where minimum string lenth is min\n- `max(value: number, errMsg?: string) => StringType`  \n   returns a new string schema where maximum string length is max\n- `pattern(value: RegExp, errMsg?: string) => StringType`  \n   returns a new string schema where string must match pattern\n- `valid(list: string[], errMsg?: string) => StringType`  \n   returns a new string schema where string must be included in valid string array\n- `withPredicate(fn: (val: string) => boolean), errMsg?: string }`  \n   returns a new schema where string must pass predicate function(s).\n- `default(value: string | (() => string)) => StringType`  \n   returns a new schema which will use defaultValue when parsing undefined\n\noptions can be passed as an option object or chained from schema.\n\n```typescript\nmyzod.string({ min: 3, max: 10, pattern: /^hey/ });\n// same as\nmyzod.string().min(3).max(10).pattern(/^hey/);\n```\n\nThe valid options lets you validate against a set of strings.\n\n```typescript\nconst helloworld = myzod.string().valid(['hello', 'world']);\ntypeof HelloWorld = myzod.Infer<typeof helloworld>; // => string\n```\n\nif however you want the strings to be typed used the [literals](#literals) helper function:\n\n```typescript\nconst helloworld = myzod.literals('hello', 'world');\ntype HelloWorld = myzod.Infer<typeof helloworld>; // => 'hello' | 'world'\n```\n\nMyzod is not interested in reimplementing all possible string validations, ie isUUID, isEmail, isAlphaNumeric, etc. The myzod string validation can be easily extended via the withPredicate API.\n\n```typescript\nconst uuidSchema = myzod.string().withPredicate(validator.isUUID, 'expected string to be uuid');\n\ntype UUID = Infer<typeof uuidSchema>; // => string\n\nuuidSchema.parse('hello world'); // Throws ValidationError with message 'expected string to be uuid'\n// note that if predicate function throws an error that message will be used instead\n```\n\nNote that you can register multiple predicates, and that each invocation will create a new schema:\n\n```typescript\nconst greeting = myzod.string().withPredicate(value => value.startsWith('hello'), 'string must start with hello');\nconst evenGreeting = greeting.withPredicate(value => value.length % 2 === 0, 'string must have even length');\nconst oddGreeting = greeting.withPredicate(value => value.length % 2 === 1, 'string must have odd length');\n```\n\nYou can use default values or functions to create default values for myzod string schemas.\n\n```typescript\nconst uuidSchema = z.string().default(() => uuidv4());\nconst val = uuidSchema.parse(undefined); // val is a valid uuid constructed by uuidv4()\nuuid.parse(null); // throws an error\n```\n\n#### Number\n\noptions:\n\n- min: `number` - min value for number\n- max: `number` - max value for number\n- coerce: `boolean` - when true will attempt to coerce strings to numbers. default `false`\n\nmethods:\n\n- `min(value: number, errMsg?: string) => NumberType`  \n  returns a new number schema where number must be greater than or equal to min value\n- `max(value: number, errMsg?: string) => NumberType`  \n   returns a new number schema where number must be less than or equal to max value\n- `withPredicate(fn: (value: number) => boolean, errMsg?: string) => NumberType`  \n  returns a new number schema where number must satisfy predicate function\n- `coerce(flag?: boolean) => NumberType`  \n  returns a new number schema which depending on the flag will coerce strings to numbers\n- `default(value: number | (() => number)) => NumberType`  \n   returns a new number schema which will use value as default when parsing undefined\n\noptions can be passed as an option object or chained from schema.\n\n```typescript\nmyzod.number({ min: 0, max: 10 });\n// Same as:\nmyzod.number().min(0).max(10);\n```\n\nCoercion example:\n\n```typescript\nconst schema = myzod.number().coerce(); // same as myzod.number({ coerce: true });\n\nconst value = schema.parse('42');\n\nassert.ok(typeof value === 'number'); // succeeds\nassert.equal(value, 42); // succeeds\n```\n\n#### BigInt\n\noptions:\n\n- min: `number` - min value for number\n- max: `number` - max value for number\n\nmethods:\n\n- `min(value: number | bigint) => BigIntType`  \n   returns a new bigint schema where value must be at least min\n- `max(value: number | bigint) => BigIntType`  \n   returns a new bigint schema where value must be lesser or equal to max\n- `withPredicate(fn: (value: bigint) => boolean, errMsg?: string) => BigIntType`  \n   returns a new bigint schema where value must pass predicate function\n\noptions can be passed as an option object or chained from schema.\n\n```typescript\nmyzod.bigint({ min: 0, max: 10 });\n// Same as:\nmyzod.bigint().min(0).max(10);\n\nconst integer = myzod.bigint();\ntype Integer = myzod.Infer<typeof integer>; // => bigint\n```\n\nThe bigint schema automatically coerces bigint interpretable numbers and strings into bigint values.\n\n```typescript\nconst schema = myzod.bigint();\nconst value = schema.parse('42');\n\nassert.ok(typeof value === 'bigint'); // succeeds\nassert.equal(value, 42n); // succeeds\n```\n\n#### Boolean\n\nmethods:\n\n- `default(value: boolean | (() => boolean)) => BooleanType`  \n   returns a new boolean schema instance which will use value as default when parsing undefined\n\n```typescript\nmyzod.boolean();\n```\n\n#### Undefined\n\n```typescript\nmyzod.undefined();\n```\n\n#### Null\n\nmethods:\n\n- `default() => NullType`  \n   returns a new null schema instance which will use set null as default when parsing undefined\n\n```typescript\nmyzod.null();\n```\n\n#### Literal\n\nmethods:\n\n- `default() => LiteralType`  \n   returns a new literal schema instance which will use its literal as default when parsing undefined\n\nJust as in typescript we can type things using literals\n\n```typescript\nconst schema = myzod.literal('Value');\ntype Val = Infer<typeof schema>; // => 'Value'\n```\n\nSometimes we do not want to go all out and create an enum to represent a combination of literals.\nMyzod offers a utility function to avoid have to \"or\" multiple times over many literalTypes.\n\n##### Literals\n\n```typescript\nconst schema = myzod.literals('red', 'green', 'blue');\ntype Schema = myzod.Infer<typeof schema>; // => 'red' | 'green' | 'blue'\n\n// Other equivalent ways of creating the same schema:\nconst schema = myzod.literal('red').or(myzod.literal('green')).or(myzod.literal('blue'));\nconst schema = myzod.union([myzod.literal('red'), myzod.literal('green'), myzod.literal('blue')]);\n```\n\n#### Unknown\n\nmethods:\n\n- `default(value: any | (() => any)) => UnknownType`  \n   returns a new unknown schema instance which will use value as default when parsing undefined\n\n```typescript\nmyzod.unknown();\n```\n\nThe unknown schema does nothing when parsing by itself. However it is useful to require a key to be present inside an object schema when we don't know or don't care about the type.\n\n```typescript\nconst schema = myzod.object({ unknownYetRequiredField: myzod.unknown() });\ntype Schema = Infer<typeof schema>; // => { unknownYetRequiredField: unknown }\n\nschema.parse({}); // throws a ValidationError\nschema.parse({ unknownYetRequiredField: 'hello' }); // succeeds\n```\n\n#### Object\n\noptions:\n\n- allowUnknown: `boolean` - allows for object with keys not specified in expected shape to succeed parsing, default `false`\n- suppressErrPathMsg: `boolean` - suppress the path to the invalid key in thrown validationErrors. This option should stay false for most cases but is used internally to generate appropriate messages when validating nested objects. default `false`\n\nmyzod.object is the way to construct arbitrary object schemas.\n\n```typescript\nfunction object(shape: { [key: string]: Type<T> }, opts?: options);\n```\n\nexamples:\n\n```typescript\nconst strictEmptyObjSchema = myzod.object({});\nconst emptyObjSchema = myzod.object({}, { allowUnknown: true });\n\n// Both Schemas infer the same type\ntype Empty = Infer<typeof emptyObjSchema>; // => {}\ntype StrictEmpty = Infer<typeof strictEmptyObjSchema>; // => {}\n\nemptyObjSchema.parse({ key: 'value' }); // => succeeds\nstrictEmptyObjSchema.parse({ key: 'value' }); // => throws ValidationError because not expected key: \"key\"\n\nconst personSchema = myzod.object({\n  name: myzod.string(),\n});\nconst shape = personSchema.shape(); // => returns { name: myzod.string() }\n```\n\n#### object.allowUnknownKeys\n\nA new schema can be build via fluent syntax to allow for unknown keys\n\n```typescript\nconst schema = z.object({ name: z.string(), age: z.number() }).allowUnknownKeys();\n\nconst value = schema.try({ name: 'myzod', age: 1, cool: true }); // value is { name: 'myzod', age: 1 }\n```\n\n#### object.withPredicate\n\nYou can add predicate functions to object schemas. Note that these predicate functions will not be kept around for schemas produces from object.pick/omit/partial as they predicate function signatures need to change for those signatures.\n\n```typescript\nconst registrationSchema = myzod\n  .object({\n    email: z.string().withPredicate(validator.isEmail, 'expected email'),\n    password: z.string().min(8),\n    confirmedPassword: z.string(),\n  })\n  .withPredicate(value => value.password === value.confirmedPassword, 'password and confirmed do not match');\n```\n\n#### object.shape\n\nYou can extract the shape from an ObjectType.\n\n```typescript\nconst personSchema = myzod.object({\n  name: myzod.string(),\n});\nconst shape = personSchema.shape(); // => returns { name: myzod.string() }\n```\n\n#### object.pick/omit/partial\n\nThe Object type has utility methods pick, omit, and partial for creating new ObjectType schemas based on the current instance. Note once more that predicates do not carry over from base schema.\n\n```typescript\nconst profileSchema = myzod.object({\n  id: myzod.string().predicate(validator.isUUID),\n  name: myzod.string().pattern(/[A-Z]\\w+/)\n  age: myzod.number().min(0),\n});\n\ntype Profile = myzod.Infer<typeof profileSchema>; // => { id: string; name: string; age: number }\n\nconst putProfileSchema = profileSchema.pick(['name','age']); // Same as profileSchema.omit(['id']);\n\ntype PutProfile = myzod.Infer<typeof putProfileSchema>; // => { name: string; age: number }\n\nconst patchProfileSchema = putProfileSchema.partial();\n\ntype PatchProfile = myzod.Infer<typeof patchProfileSchema>; // => { name?: string; age?: number }\n\n```\n\nPartial accepts an options object to allow for deeply nested partials:\n\n```typescript\nconst schema = myzod\n  .object({\n    name: myzod.string(),\n    birthday: myzod.object({\n      year: myzod.number(),\n      month: myzod.number().min(1).max(12),\n      date: myzod.number().min(1).max(31),\n    }),\n  })\n  .partial({ deep: true });\n\ntype DeeplyPartialSchema = myzod.Infer<typeof schema>; // { name?: string; birthday?: { year?: number; month?: number; date?: number; } }\n```\n\n#### object.default\n\nWith the default function you can set a default value for the object schema which will be used when trying to parse undefined:\n\n```typescript\nconst personSchema = myzod\n  .object({ name: myzod.string(), lastName: myzod.string() })\n  .default({ name: 'John', lastName: 'Doe' });\n\nconst person = personSchema.parse(undefined); // => { name: 'John', lastName: 'Doe' }\n```\n\n#### object.collectErrors\n\nObject schemas have an option to collect all validation errors instead of the default throwing on first error.\nThis is useful for form validation, but does incur a slight performance hit.\n\n```typescript\nconst personSchema = myzod.object({ name: myzod.string(), lastName: myzod.string() }).collectErrors();\n\npersonSchema.parse({ name: 1, lastName: 2 });\n\n// throws an ValidationError with message:\nerr.message = `\n  error parsing object at path: \"name\" - expected type to be string but got number\n  error parsing object at path: \"lastName\" - expected type to be string but got number\n`;\n\nerr.collectedErrors = {\n  name: ValidationError,\n  lastName: ValidationError,\n};\n```\n\n##### Key Signatures\n\nIn the next section myzod goes over \"records\" which is the simple and idiomatic way in typescript of describing an object with solely a key signature.\nHowever you can use key signatures directly in your object schema definitions if you like using the myzod.keySignature symbol.\n\n```typescript\nconst scores = myzod.object({ [myzod.keySignature]: myzod.number() }); // same as: myzod.record(myzod.number());\n\ntype Scores = myzod.Infer<typeof scores>; // => { [x: string]: number }\n```\n\nThe advantage of this approach is to mix statically known keys with a keysignature without intersecting records and objects.\n\n#### Record\n\nThe record function emulates as the equivalent typescript type: `Record<string, T>`.\n\n```typescript\nconst schema = myzod.record(myzod.string());\n\ntype Schema = Infer<typeof schema>; // => { [x: string] : string }\n```\n\nOne primary use case of the record type is for creating schemas for objects with unknown keys that you want to have typed. This would be the equivalent of passing a pattern to joi. The way this is done in myzod is to intersect a recordSchema with a object schema.\n\n```typescript\nconst objSchema = myzod.object({\n  a: myzod.string(),\n  b: myzod.boolean(),\n  c: myzod.number(),\n});\n\nconst recordSchema = myzod.record(zod.number());\n\nconst schema = objSchema.and(recordSchema);\n\ntype Schema = Infer<typeof schema>;\n\n// Here Schema is the same as the following type definition:\ntype Schema = {\n  a: string;\n  b: boolean;\n  c: number;\n  [key: string]: number;\n};\n```\n\nAs a utility you can pick directly from a recordSchema and get an equivalent objectSchema:\n\n```typescript\nconst recordSchema = z.record(z.string());\n\ntype RecordType = z.Infer<typeof recordSchema>; // => { [x: string]: string }\n\nconst objSchema = recordSchema.pick(['a', 'b']);\n\ntype ObjType = z.Infer<typeof objSchema>; // => { a: string; b: string; }\n```\n\nAs a utility for creating records whose values are by default optional, you can use the myzod.dictionary function.\n\n```typescript\nconst schema = myzod.dictionary(myzod.string());\n// same as\nconst schema = myzod.record(myzod.string().optional());\n\ntype Schema = Infer<typeof schema>; // => { [key: string]: string | undefined }\n\n// Note I have experienced issues with vscode type hints omitting the undefined union\n// however when running tsc it evaluates Schema as the type above.\n```\n\n#### Array\n\noptions:\n\n- length: `number` - the expected length of the array\n- min: `number` - the minimum length of the array\n- max: `number` - the maximum length of the array\n- unique: `boolean` - should the array be unique. default `false`\n- coerce: `(value: string) => T[]` - function to coerce string representations to an array\n\nmethods:\n\n- `length(value: number, errMsg?: string) => ArrayType<T>`  \n  returns a new array schema of the same type where the length of the array must be value\n- `min(value: number, errMsg?: string) => ArrayType<T>`  \n  returns a new array schema of the same type where the minimum length is value\n- `max(value: number, errMsg?: string) => ArrayType<T>`  \n  returns a new array schema of the same type where the maximum length is value\n- `unique() => ArrayType<T>`  \n  returns a new array schema of the same type where every element must be unique\n- `withPredicate(fn: (value: T[]) => boolean, errMsg?: string) => ArrayType<T>`  \n  returns a new array schema that must respect predicate function\n- `default(value: T[] | (() => T[])) => ArrayType<T>`  \n   returns a new array schema that will use value as default when parsing undefined\n- `coerce(fn: (value: string) => T[]) => ArrayType<T>`  \n   returns a new array schema that will coerce string representations using given function\n\nSignature:\n\n```typescript\nfunction array(schema: Type<T>, opts?: Options);\n```\n\nExample:\n\n```typescript\nconst schema = myzod.array(myzod.number()).unique();\n\ntype Schema = Infer<typeof schema>; // => string[]\n\nschema.parse([1, 1, 2]); // => throws ValidationError\n```\n\nMyzod allows for string representations to be coerced to the array of your type via a coercion function. A common example is when parsing csv values.\n\n```typescript\nconst schema = myzod.array(myzod.string()).coerce((csv: string) => csv.split(','));\nconst result = schema.try('red,blue,green');\n\n// result === ['red', 'blue', 'green'];\n```\n\n#### Tuple\n\nmethods:\n\n- `withPredicate(fn: (value: Infer<TupleType<T>>) => boolean, errMsg?: string) => TupleType<T>`  \n  returns a new tuple type that must respect predicate function\n- `default(value: InferTupleType<T>) => TupleType<T>`  \n   returns a new tuple type schema that will use value as default when parsing undefined\n\nTuples are similar to arrays but allow for mixed types of static length.\nNote that myzod does not support intersections of tuple types at this time.\n\n```typescript\nconst schema = myzod.tuple([myzod.string(), myzod.object({ key: myzod.boolean() }), myzod.array(myzod.number())]);\n\ntype Schema = Infer<typeof schema>; // => [string, { key: boolean; }, number[]];\n```\n\n#### Enum\n\nmethods:\n\n- `default(value: Enum | (() => Enum)) => EnumType`  \n   returns a new enum schema instance which will use value as default when parsing undefined\n\nThe enum implementation differs greatly from the original zod implementation.\nIn zod you would create an enum schema by passing an array of litteral schemas.\nI, however, did not like this since enums are literals they must by typed out in the source code regardless, and I prefer to use actual typescript `enum` values.\n\nThe cost of this approach is that I cannot statically check that you are passing an enum type to the zod.enum function. If you pass another value it won't make sense within the type system. Users beware.\n\n```typescript\nenum Color {\n  red = 'red',\n  blue = 'blue',\n  green = 'green',\n}\n\nconst colorSchema = zod.enum(Color);\n\nInfer<typeof colorSchema> // => Color -- Redundant\n\nconst color = colorSchema.parse('red');\n```\n\nThe enum schema provides a check method as a typeguard for enums.\n\n```typescript\nconst value: string = 'some string variable';\nif (colorSchema.check(value)) {\n  // value's type is Color within this if block\n}\n```\n\nThe enum type also accepts an options object as a second parameter.\n\nYou can set `coerce` to `'lower'` or `'upper'` to ignore string casing when calling `check` or `parse`.\n\n```typescript\nz.enum(Colors, { coerce: 'lower' });\nconst value: string = 'Red';\ncolorSchema.parse(value);\n// parse will return a lowercased value\n```\n\nYou can also set a default value in the options object.\n\n```typescript\nz.enum(Colors, { defaultValue: 'red' });\n```\n\n#### Date\n\nmethods:\n\n- `withPredicate(fn: (value: Date) => boolean, errMsg?: string) => DateType`  \n   returns a new date schema where value must pass predicate function(s)\n- `default(value: Date | (() => Date)) => DateType`  \n   returns a new date schema which will use value as default when parsing undefined\n\nthe myzod.date function creates a date schema. Values that will be successfully parsed by this schema are\nJavascript Date instances and valid string representations of dates. The returned parse Date will be an instance of Date.\n\n```typescript\nconst schema = myzod.date();\ntype Schema = myzod.Infer<typeof schema>; // => Date\n\nconst date = new Date();\nschema.parse(date); // returns date\nschema.parse(date.toISOString()); // returns a date instance equal to date\n\n// WithPredicate example\nconst weekDay = myzod\n  .date()\n  .withPredicate(date => date.getUTCDate() !== 6 && date.getUTCDate() !== 0, 'expected weekday');\n```\n\n#### Union\n\nThe myzod.union function accepts an arbitrary number of schemas and creates a union of their inferred types.\n\n```typescript\nconst schema = myzod.union([myzod.string(), myzod.array(myzod.string()), myzod.number()]);\n\ntype Schema = Infer<typeof schema>; // => string | string[] | number\n```\n\n#### Intersection\n\nThe myzod.intersection takes two schemas as arguments and creates an intersection between their types.\n\n```typescript\nconst a = myzod.object({ a: myzod.string() });\nconst b = myzod.object({ b: myzod.string() });\n\nconst schema = myzod.intersection(a, b);\n// same as\nconst schema = a.and(b);\n// or\nconst schema = b.and(a);\n\ntype Schema = Infer<typeof schema>; // => { a: string; b: string }\n```\n\n#### Partial\n\nThe myzod.partial function takes a schema and generates a new schema equivalent to typescript's Partial<T> type for that schema.\n\n```typescript\nconst personSchema = myzod.object({ name: myzod.string() });\nconst partialPersonSchema = myzod.partial(personSchema);\n\ntype PartialPerson = Infer<typeof partialPersonSchema>; // => Partial<{ name: string }> || { name?: string }\n\npartialPersonSchema.parse({}); // Succeeds\npartialPersonSchema.parse({ nickName: 'lil kenny g' }); // throws validation error\n```\n\nThe partial function accepts an options object as second argument to create a deeply partial object.\n\noptions:\n\n- deep: `boolean` created a deeply partial schema for nested objects\n\n```typescript\nconst schema = myzod.object({\n  name: myzod.string(),\n  birthday: myzod.object({\n    year: myzod.number(),\n    month: myzod.number().min(1).max(12),\n    date: myzod.number().min(1).max(31),\n  }),\n});\n\nconst partialSchema = myzod.partial(schema);\n\ntype PartialSchema = myzod.Infer<typeof partialSchema>; // => { name?: string; birthday?: { year: number; month: number; date: number; } }\n\nconst deeplyPartialSchema = myzod.partial(schema, { deep: true });\n\ntype DeeplyPartialSchema = myzod.Infer<typeof deeplyPartialSchema>; // { name?: string; birthday?: { year?: number; month?: number; date?: number; } }\n```\n\n#### Pick\n\nThe myzod.pick function takes a myzod schema and an array of keys, and generates a new schema equivalent to typescript's Pick<T, keyof T> type.\n\n```typescript\nconst personSchema = myzod.object({\n  name: myzod.string(),\n  lastName: myzod.string(),\n  email: myzod.email(),\n  age: myzod.number(),\n});\n\nconst nameSchema = myzod.pick(personSchema, ['name', 'lastName']);\n\ntype Named = myzod.Infer<typeof nameSchema>; // => { name: string; lastName: string; }\n```\n\n#### Omit\n\nThe myzod.pick function takes a myzod schema and an array of keys, and generates a new schema equivalent to typescript's Omit<T, keyof T> type.\n\n```typescript\nconst personSchema = myzod.object({\n  name: myzod.string(),\n  lastName: myzod.string(),\n  email: myzod.email(),\n  age: myzod.number(),\n});\n\nconst nameSchema = myzod.omit(personSchema, ['email', 'age']);\n\ntype Named = myzod.Infer<typeof nameSchema>; // => { name: string; lastName: string; }\n```\n\n#### Lazy\n\nThe myzod.lazy function takes a function that returns a schema and lazily evaluates it at parse. The advantage with this approach is that you can create schemas that reference themselves. Unfortunately typescript cannot resolve this type and it will be the user's responsibility to provide the corresponding myzod type. Fortunately if the user's provided type is incompatible with the given schema it will fail to compile so there is some hope.\n\n```typescript\ntype Person = {\n  name: string;\n  friends: Person[];\n};\n\nconst personSchema: z.Type<Person> = myzod.object({\n  name: myzod.string(),\n  friends: myzod.array(myzod.lazy(() => personSchema)),\n});\n```\n","readmeFilename":"readme.md"}