Created
October 19, 2022 21:35
-
-
Save ciiqr/b467e5baee7981e17dd4d79da303d31b to your computer and use it in GitHub Desktop.
zod numeric string to number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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