Skip to content

Instantly share code, notes, and snippets.

@ciiqr
Created October 19, 2022 21:35
Show Gist options
  • Save ciiqr/b467e5baee7981e17dd4d79da303d31b to your computer and use it in GitHub Desktop.
Save ciiqr/b467e5baee7981e17dd4d79da303d31b to your computer and use it in GitHub Desktop.
zod numeric string to number
import { z } from "zod";
export function zStringToNumber() {
return z.preprocess((a) => {
const stringRes = z.string().safeParse(a);
if (!stringRes.success) {
return a;
}
const numberRes = Number.parseInt(stringRes.data);
if (Number.isNaN(numberRes)) {
return a;
}
return numberRes;
}, z.number());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment