generated at
zod.coerce()
Zod v3.20で入った





stringに対して使っている例
ts
const schema = z.coerce.string(); schema.parse("tuna"); // => "tuna" schema.parse(12); // => "12" schema.parse(true); // => "true"
これは、zod.preprocess()を使って以下のように書いているのと同じ
ts
z.preprocess(String, z.string())
coerce() のほうがchainしやすくて良さそうねmrsekut
と、思ったがpreprocessの方でもzod.pipeを併用したら同じことが出来る

どのprimitive型に対しても使える
ts
z.coerce.string(); // String(input) z.coerce.number(); // Number(input) z.coerce.boolean(); // Boolean(input) z.coerce.bigint(); // BigInt(input) z.coerce.date(); // new Date(input)


numberに対して使って、number以外が来た時はちゃんとerrorになる
ts
z.coerce.number().parse('hoge') // errror