パース後にデータを変換するにはtransform
を使用します。
以下に使用例を示します。
数値を文字列に変換
import { z } from 'zod';
// 数値から文字列への変換
const numberToString = z.number().transform(num => num.toString());
// バリデーションと変換
const result = numberToString.parse(123); // "123"
オブジェクトのプロパティを変換
import { z } from 'zod';
// オブジェクトスキーマの定義
const originalSchema = z.object({
name: z.string(),
age: z.number(),
});
// ageプロパティを文字列に変換する新しいスキーマ
const transformedSchema = originalSchema.transform(obj => ({
...obj,
age: obj.age.toString(),
}));
// バリデーションと変換
const result = transformedSchema.parse({ name: 'John', age: 30 }); // { name: 'John', age: '30' }
オブジェクトのキーをキャメルケースに変換
import { z } from 'zod';
function toCamelCase(str: string): string {
return str.replace(/([-_][a-z])/g, group => group.toUpperCase()
.replace('-', '')
.replace('_', ''));
}
const originalSchema = z.object({
first_name: z.string(),
last_name: z.string(),
});
const transformedSchema = originalSchema.transform(obj => {
const newObj: any = {};
for (const key in obj) {
newObj[toCamelCase(key)] = obj[key];
}
return newObj;
});
const result = transformedSchema.parse({ first_name: 'John', last_name: 'Doe' });
// result: { firstName: 'John', lastName: 'Doe' }