profile
viewpoint

chrbala/parse-redux 19

Drop-in replacement for Parse with added Redux goodness!

chrbala/react-audio 17

HTML 5 Audio API in React

chrbala/react-resume-boilerplate 9

a way to jump start writing your resume and cover letter in HTML and CSS

chrbala/horizon-react-webpack-hmr-boilerplate 4

A semi-opinionated boilerplate for horizon-react and webpack, with hot module reloading

chrbala/lmdb-leveldown 2

leveldown compatible binding to LMDB

chrbala/apollo-tooling 0

✏️ Tooling for development and production Apollo workflows

chrbala/chrbala-rollup 0

My rollup config

chrbala/create-react-app 0

Create React apps with no build configuration.

pull request commentcolinhacks/zod

Add support for Deno

I've been trying some workarounds for making isolated modules work in 3.7 (without import type), but it's not looking too promising. You can explicitly re-export types, but it's verbose, requires a lot of duplication for generic types, and seems to create visibility issues:

Exported type alias 'TypeOf' has or is using private name ''.ts(4081)

We may not merge it, but for TypeScript 3.8 and Deno, I have an updated working branch in #247, if any other Deno users want something they can use Right Now.

wilmveel

comment created time in 4 hours

PR opened colinhacks/zod

Deno support, given isolated modules

For the discussion in #209, this draft PR brings together isolated modules support (#246), @wilmveel's test refactoring, a simpler Deno transformation script (I'd rather not use the complicated dependency, it turns out our needs can be covered by a pretty simple script), and GitHub actions to automatically rebuild the Deno version and test across Deno and Node.

+10284 -5843

0 comment

143 changed files

pr created time in 7 hours

issue commentcolinhacks/zod

Generating Zod schema from TS type definitions

I love this idea that @flybayer suggested, which was partially implemented in the tozod library. ❤️

I'm looking to implement Zod in my project, but it seems like I need to strip out pretty much all of my current type definitions and replace them with Zod schemas. That effectively puts Zod in charge of my type system, which I don't like; in my opinion, Typescript should be the master of typing, and Zod should be the master of validation. One way to do that would be to make the schemas conform to my existing type system in the way flybayer suggested.

tozod was a great step in the right direction, but it isn't sufficient as it is. It either needs to be built out a lot more or we need another solution. Is this something that can be pursued?

To put it a different way, Zod is advertised as "Typescript first", but right now it feels more like "Zod first with Typescript as a close second". I say that because, currently, you have to write the Zod schemas first, then use them to generate types (not doing it this way leads to messy situations). To be truly "Typescript first", the Typescript types have to be king, and the schemas should conform to the types instead of (or in addition to) the types being generated from the schemas.

Would it be helpful to open this as a separate issue? I know it is not really what the author requested and is technically off topic 😜

I mean that is pretty much what the project i had started does precisely, @derekparsons718

danenania

comment created time in 7 hours

PR opened colinhacks/zod

Isolated modules

For the discussion of Deno support at #209, this draft PR demonstrates changes to support TypeScript's isolateModules mode.

The meaningful changes are limited to changing some exports to export types, and importing Jest's test helpers explicitly instead of relying on global context. Isolated modules mode requires TypeScript to be able to understand each module in isolation, without that context.

However, this required raising the minimum supported version from TypeScript 3.7 to 3.8, which in turn requires updating several other dependencies, so most of this PR is meaningless changes from Prettier.

The compatibility hit might not make sense for Zod 2.0, but perhaps it would make sense some time in the future.

+1854 -5642

0 comment

56 changed files

pr created time in 8 hours

issue commentcolinhacks/zod

Generating Zod schema from TS type definitions

I love this idea that @flybayer suggested, which was partially implemented in the tozod library. ❤️

I'm looking to implement Zod in my project, but it seems like I need to strip out pretty much all of my current type definitions and replace them with Zod schemas. That effectively puts Zod in charge of my type system, which I don't like; in my opinion, Typescript should be the master of typing, and Zod should be the master of validation. One way to do that would be to make the schemas conform to my existing type system in the way flybayer suggested.

tozod was a great step in the right direction, but it isn't sufficient as it is. It either needs to be built out a lot more or we need another solution. Is this something that can be pursued?

To put it a different way, Zod is advertised as "Typescript first", but right now it feels more like "Zod first with Typescript as a close second". I say that because, currently, you have to write the Zod schemas first, then use them to generate types (not doing it this way leads to messy situations). To be truly "Typescript first", the Typescript types have to be king, and the schemas should conform to the types instead of (or in addition to) the types being generated from the schemas.

Would it be helpful to open this as a separate issue? I know it is not really what the author requested and is technically off topic 😜

danenania

comment created time in 12 hours

issue openedcolinhacks/zod

Question: How to validate a set of properties as required?

Firstly, thanks for zod. I found some of the other tools in your comparison, but zod is the one that really seems to fit for my use case. Plus, I'm deeply impressed by the 3 letter name which was unused in npm and elsewhere! :-)

I have 3 properties, foo, bar and baz. If bar is present, then so must be baz. In other words, bar and baz must always be present or absent together. I couldn't figure out how to achieve this result in TypeScript, maybe I need union interfaces, I'm not sure. Is there a way to do it in zod?

I created a duplicate type that requires both bar and baz and I use that inside .refine() with a .check(), but I wonder if there's a clearer way to express what I'm trying to do?

created time in 13 hours

issue openedcolinhacks/zod

Representing a function with additional properties

Is it possible to represent a function that also has some additional properties on it?

Thinking specifically of cases like Storybook stories:

// Simplified from the real type
interface Story<Args, StoryFnReturnType> {
  (args: Args): StoryFnReturnType;
  storyName?: string;
}

These are functions with properties added onto them. Something like

function SomeFunc() {
  // ...
}

SomeFunc.storyName = "hello there";

I haven't been able to find any existing issues or documentation around this, but let me know if this has already been brought up. I also understand if this is too challenging or not a priority to implement.

Thanks!

created time in 13 hours

issue openedcolinhacks/zod

Validation order 2.0.0-beta.25

Hi,

I've created a sandbox for a situation, when validation rules take strange order.

Assuming having a schema like this const formValuesSchema = z.object({ name: z.string(), company: z.string(), email: z.string().email() });

I don't get an Invalid email error when email is filled, until the other fields are filled as well. It happens on version 2.0.0-beta.25

https://codesandbox.io/s/elegant-drake-4ultm?fontsize=14&hidenavigation=1&theme=dark&file=/src/index.ts:27-137

created time in 17 hours

issue commentcolinhacks/zod

Zod 2 - parseAsync breaks unions of objects

@colinhacks Thank you, the original snippet works correctly. But I have another one:

import * as z from 'zod';

const Schema = z.union([
	z.object({
		statusCode: z.literal(200),
		body: z.object({
			id: z.string(),
		}),
	}),
	z.object({
		statusCode: z.literal(403),
		body: z.object({
			message: z.string(),
			reason: z.string().nullable(),
		}),
	}),
]);

(async () => {
	const obj = { statusCode: 200, body: { id: "f8a2ebc9-72ba-4f45-ad4d-16f956259ed3" } };
	console.log(Schema.parse(obj)); // Works
	console.log(await Schema.parseAsync(obj)); // Error
})();
mpartel

comment created time in a day

issue commentcolinhacks/zod

Request for help: typed Zod combinator with dynamic field name

I was aware of this syntax but I couldn't get it to work regardless. Consider this implementation:

const test = <T extends string>(key:T)=>{
  return {[key]: 25};
}

TypeScript isn't able to infer the return type ({ asdf: number}) using the dynamic field names syntax.

Screen Shot 2020-12-01 at 10 21 11 PM

lilred

comment created time in a day

pull request commentcolinhacks/zod

Add support for Deno

Done! Thanks for the guidance @jeremyBanks.

Btw, Zod v2 is coming out of beta shortly and I've bumped the minimum TypeScript version to 3.7. That may help with these efforts.

wilmveel

comment created time in a day

push eventcolinhacks/zod

Carl Patenaude-Poulin

commit sha 74ae2632146323635ba529f99579993725786875

Remove broken link

view details

Carl Patenaude-Poulin

commit sha f4be032df09ae7daea01501cd702c0347fc5d44d

Fix typo

view details

Colin McDonnell

commit sha 427d2edd9c6cf19fb9f58ec7e05425dc7209118a

Merge pull request #242 from lilred/patch-1 Docs fixes

view details

push time in a day

PR merged colinhacks/zod

Docs fixes
+1 -2

0 comment

2 changed files

lilred

pr closed time in a day

push eventcolinhacks/zod

Colin McDonnell

commit sha 18c8ddb122005a74e7fd11d5ddf0ffface8fd957

2.0.0-beta.25

view details

push time in a day

issue closedcolinhacks/zod

Skip regex() when optional() and string is empty ""

It makes more sense to only go through regex when the value is not empty for optional(), it removes overhead and it makes things more elegant. Currently to accomplish this requirement we need to allow empty in regex or to remove the empty fields from the formData before passing it to .parse

// Middle Name(optional)
const middleName = zod.string().optional().regex(/^[a-zA-Z0-9]+$/, { message: "Only alphabets and numbers are allowed." })
middleName.parse("");  // returns regex error message

My current workaround but honestly it really shouldn't go to that step since there's no need for regex to validate an empty string

// prepend $| to allow empties
const middleName = zod.string().optional().regex(/^$|[a-zA-Z0-9]+$/, { message: "Only alphabets and numbers are allowed." })

closed time in a day

cybervaldez

issue commentcolinhacks/zod

Skip regex() when optional() and string is empty ""

I don't support this, seems like a weird edge case. The regex checks should be run on any string that gets passed in. I recommend using a custom refinement:

zod.string().optional().refine(val => {
  return (val === "" || /^[a-zA-Z0-9]+$/.test(val));
}, { message: "Only alphabets and numbers are allowed." })
cybervaldez

comment created time in a day

issue closedcolinhacks/zod

Refine is taking precedence over optional, nullable, nonempty

I've been using .regex for my validations and recently saw a tip in the docs to use validator.js for that so I went ahead and tried it out using refine, now the problem is refine seems to take precedence over optional, nullable, nonempty.

import * as zod from "zod";

import isDate from 'validator/es/lib/isDate'
import toDate from 'validator/es/lib/toDate'

let test = zod.string().optional().nullable().refine(isDate, { message : "Please use the format YYYY-MM-DD(e.g 1986-02-20, 1986/02/20)" })
console.log(test.safeParse("")) // error
console.log(test.safeParse(null)) // error
console.log(test.safeParse(undefined)) // error

closed time in a day

cybervaldez

issue commentcolinhacks/zod

Refine is taking precedence over optional, nullable, nonempty

This is expected. If you just want to refine the string schema, you should move the call to .refine:

zod.string().refine(isDate, { message : "Please use the format YYYY-MM-DD(e.g 1986-02-20, 1986/02/20)" }).optional().nullable();

Calling X.optional() is equivalent to z.union([X, z.undefined()]).

cybervaldez

comment created time in a day

issue commentcolinhacks/zod

Zod 2 - parseAsync breaks unions of objects

Looks like there were multiple bugs in play here. I fixed one problem with how objects get parsed but there was another issue with unions. I can confirm the original snippet now runs correctly with beta 25 (and it's been added to the test suite!).

mpartel

comment created time in a day

PR opened colinhacks/zod

Remove broken link in README.md
+0 -1

0 comment

1 changed file

pr created time in a day

issue openedcolinhacks/zod

Generic transformers?

Thanks for a great library! Was doing some exploration for using, and was wondering if there was a way to make a "generic" transformer-like thing. I have a generic type called Serialized which basically maps a type that contains dates (recursively) to a type that swaps those properties for strings. This type is used for Postgres to_json and over-the-wire dates from API to client. It looks like:

export type Serialized<T> = {
  [P in keyof T]: T[P] extends Date
    ? string
    : T[P] extends Date | null
    ? string | null
    : T[P] extends any[]
    ? Serialized<T[P]>
    : T[P] extends any[] | null
    ? Serialized<T[P]> | null
    : T[P] extends object
    ? Serialized<T[P]>
    : T[P];
};

In my code, I'm currently manually creating transformers that extend the base schema and replace the date(|null) properties with string(|null) manually, but I was wondering if there was a way to abstract that out such that I could, in essence, build up the ZodObject._shape dynamically?

created time in 2 days

issue openedcolinhacks/zod

Skip regex() when optional() and string is empty ""

It makes more sense to only go through regex when the value is not empty for optional(), it removes overhead and it makes things more elegant. Currently to accomplish this requirement we need to allow empty in regex or to remove the empty fields from the formData before passing it to .parse

// Middle Name(optional)
const middleName = zod.string().optional().regex(/^[a-zA-Z0-9]+$/, { message: "Only alphabets and numbers are allowed." })
middleName.parse(""); 

My current workaround but honestly it really shouldn't go to that step since there's no need for regex to validate an empty string

// prepend $| to allow empties
const middleName = zod.string().optional().regex(/^$|[a-zA-Z0-9]+$/, { message: "Only alphabets and numbers are allowed." })

created time in 2 days

issue commentcolinhacks/zod

Zod 2 - parseAsync breaks unions of objects

Can confirm with beta.23 and beta.24.

mpartel

comment created time in 2 days

issue commentcolinhacks/zod

Zod 2 - parseAsync breaks unions of objects

@colinhacks Hi, when I try to run the snippet from the top, I still get an error with parseAsync. Tested with beta.23 and beta.24. The same result. @mpartel Can you confirm that I'm right? Or am I doing something wrong?

Thank you

mpartel

comment created time in 2 days

pull request commentcolinhacks/zod

Add support for Deno

@colinhacks You may want to consider registering the zod name on deno.land/x now rather than later, even if Deno isn't supported yet, to avoid having someone else take the name. You don't need to do anything on deno.land, you just need to add a webhook on GitHub:

  • Navigate to the repository you want to add.
  • Go to the Settings tab.
  • Click on the Webhooks tab.
  • Click on the Add webhook button.
  • Enter the URL https://api.deno.land/webhook/gh/zod?subdir=deno_lib%2F in the payload URL field.
  • Select application/json as the content type.
  • Select Let me select individual events.
  • Select only the Branch or tag creation event.
  • Press Add webhook.

(We may need to change that URL to https://api.deno.land/webhook/gh/zod?subdir=deno_lib%2F in the future, but I don't think we can use a currently-nonexistent path, so the above works for now.)

wilmveel

comment created time in 2 days

pull request commentcolinhacks/zod

Add support for Deno

It would be a shame if we couldn't publish Zod to deno.land/x. Zod's zero NPM dependencies make it's a very good candidate for use in Deno (beyond its existing merits), and it would be nice to be able to use it in packages that stay within the deno.land package ecosystem for stability.

I don't think it's possible to avoid committing the generated Deno duplicate of the code, but I'll see if we can work-around the import type issue without breaking 3.2 compatibility. We could add an Action to automatically generate and commit the Deno version of the code whenever changes are pushed (or maybe only when sent for pull requests?) to reduce the overhead.

wilmveel

comment created time in 2 days

issue commentcolinhacks/zod

Generate an ESM bundle

@colinhacks FYI using the ESM built off the v2 branch with tsc --p tsconfig.esm.json appears to work in our app, even w/ the circular dependency, but we haven't fully exercised it.

hmaurer

comment created time in 2 days

issue openedcolinhacks/zod

Refine is taking precedence over optional, nullable, nonempty

I saw a tip in the Docs to use validator-js to to extend validation so I proceeded to do that using refine, now the problem is refine seems to take precedence over optional, nullable, nonempty. I originally was using Regex for this which worked correctly.

import * as zod from "zod";

import isDate from 'validator/es/lib/isDate'
import toDate from 'validator/es/lib/toDate'

let test = zod.string().optional().nullable().refine(isDate, { message : "Please use the format YYYY-MM-DD(e.g 1986-02-20, 1986/02/20)" })
console.log(test.safeParse("")) // error
console.log(test.safeParse(null)) // error
console.log(test.safeParse(undefined)) // error

created time in 2 days

issue commentcolinhacks/zod

Generate an ESM bundle

FWIW, it's being worked on: https://github.com/rollup/plugins/pull/658

hmaurer

comment created time in 2 days

more