验证 serialize/deserialize 可以正确处理 BigInt、Date、Map、Set 等特殊类型
原生 JSON.stringify() 遇到 BigInt 会抛出错误:
"TypeError: Do not know how to serialize a BigInt"
在区块链、金融应用中,BigInt 是常见类型(如 wei、satoshi 等),必须正确处理。
| tokenAmount: | 1234567890123456789012345678901234567890 | BigInt |
| gasLimit: | 21000 | BigInt |
| createdAt: | Mon Jan 01 2024 00:00:00 GMT+0000 (Coordinated Universal Time) | Date |
| username: | alice | String |
包含 BigInt、Date、Map、Set 的深层嵌套结构
const form = useFormState({
fields: {
tokenAmount: { defaultValue: 123456789n }
}
});
// ❌ 会抛出 TypeError
const json = JSON.stringify(form._manager.getValues());import { useFormState, safeStringify, safeParse } from '@packages/formstate/src';
const form = useFormState({
fields: {
tokenAmount: { defaultValue: 123456789n }
}
});
// ✅ 使用 safeStringify
const json = safeStringify(form._manager.getValues());
// ✅ 还原
const restored = safeParse(json);
console.log(typeof restored.tokenAmount); // 'bigint'
// ✅ 或直接使用 form.serialize()
const serialized = form._manager.serialize();