question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

feature request: zod.fallback() and zod.catch()

See original GitHub issue

zod is awesome!

Maybe this is already possible, but often I need more granular control of safeParse-like behavior… Something like:

const color = string().fallback('#000000');
const person = object({ name: string(), age: number() }).fallback({});

Or, maybe with more granular control (e.g. have the fallback be based on a ZodError):

const person = object( {name: string(), age: number() }.catch(err =>  { console.error(err.message); return {} );

(so .fallback(foo) is just .catch(() => foo)).

Thanks for listening/considering!

ps: some of this might be doable with any().transform(val => xxx).string() but seems super hacky and non zod-like since you basically have to use JS/TS to coerce the value…

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:4
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

5reactions
ehahn9commented, May 29, 2021

In case anyone comes across this in the future, here’s an even better (IMHO) approach which does not involve safeParse etc.:

import { any } from 'zod';

/**
 * Create a schema matches anything and returns a value. Use it with `or`:
 *
 * const schema = zod.number();
 * const tolerant = schema.or(fallback(-1));
 *
 * schema.parse('foo')      // => ZodError
 * tolerant.parse('foo')    // -1
 */
export function fallback<T>(value: T) {
  return any().transform(() => value);
}
1reaction
ehahn9commented, Mar 9, 2021

Awesome @colinhacks. Totally agree about keeping out of core… Feel free to close this whenever you like!

Just to clarify my OP, the fallback value isn’t always compatible with Schema<T>. I’ve found this idiom most useful when I want to read an array of values (e.g. firestore records) but be tolerant of bad values:

// get some things, ignoring the invalid entries:
const things = zod.array(fallback(thingSchema, false))
const goodThings = compact(things)
Read more comments on GitHub >

github_iconTop Results From Across the Web

conform-to/zod - NPM Package Overview - Socket.dev
Start using Socket to analyze @conform-to/zod and its 0 dependencies ... The resolve(schema).validate API is also replaced by validate() :.
Read more >
express-zod-api - npm
A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.
Read more >
Colin McDonnell (@colinhacks) / Twitter
Zod 3.20 is here! This is a big one. `z.coerce` `.pipe()` `.catch()` `z.symbol()` `z.number().finite()` `z.string().datetime()` ...
Read more >
Validating Input with Zod in TypeScript - Morioh
Don't worry we will get to more complicated validations later in this article. All you need to do is: Import Zod; Create a...
Read more >
Validating Remix Form Data Using Zod and TypeScript in ...
You can use Zod to validate form input and create typed TypeScript objects ... The FormData that remix is posting with the request...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found