.preprocess()
を使用することで、スキーマのバリデーション前にデータを変換できます。
使用方法
.preprocess()
は、引数として関数を受け取ります。この関数は、バリデーション前の元のデータを引数として受け取り、変換後のデータを返します。
const castToString = z.preprocess((val) => String(val), z.string())
console.log(castToString.parse(123)); // '123'
console.log(castToString.parse(true)); // 'true'
console.log(castToString.parse({foo: 'bar'})); // '[object Object]'
上記のようにデータの型を強制するだけであればcoerce
が使用できます。
const schema = z.coerce.string()
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"