Skip to content

Parsing a numeric string #330

Answered by JLarky
imsergiobernal asked this question in Q&A
Mar 8, 2021 · 17 comments · 45 replies
Discussion options

You must be logged in to vote

I think this would be the answer, zod has it's own utility to quickly coerce the type:

console.log(z.coerce.string().parse(1));   // "1"
console.log(z.coerce.string().parse('1')); // "1"
console.log(z.coerce.number().parse(1));   //  1
console.log(z.coerce.number().parse('1')); //  1

If you want a bit more control you should look into preprocess

console.log(z.preprocess((x) => '' + x, z.string()).parse(1));      // "1"
console.log(z.preprocess((x) => Number(x), z.number()).parse('1')); //  1

or transform and pipe

console.log(z.union([z.string(), z.number()]).transform((x) => '' + x).pipe(z.string()).parse(1));      // "1"
console.log(z.union([z.string(), z.number()]).transform((x) => Number(

Replies: 17 comments 45 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
11 replies
@scotttrinh
Comment options

@linde12
Comment options

@cyrilchapon
Comment options

@kellyrmilligan
Comment options

@KeisukeNagakawa
Comment options

Comment options

You must be logged in to vote
3 replies
@smeijer
Comment options

@smeijer
Comment options

@Enteleform
Comment options

Comment options

You must be logged in to vote
1 reply
@kellyrmilligan
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@pke
Comment options

@lzehrung
Comment options

@iamadetoye
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
19 replies
@prscoelho
Comment options

@cellulosa
Comment options

@JacobWeisenburger
Comment options

@cellulosa
Comment options

@JacobWeisenburger
Comment options

Comment options

You must be logged in to vote
2 replies
@shimon-technonext
Comment options

@kellyrmilligan
Comment options

Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@JacobWeisenburger
Comment options

@zhe
Comment options

@zhe
Comment options

Comment options

You must be logged in to vote
2 replies
@pke
Comment options

@patlux
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@grundb
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet