BigInt & 特殊类型序列化测试

验证 serialize/deserialize 可以正确处理 BigInt、Date、Map、Set 等特殊类型

⚠️ 为什么需要安全序列化?

原生 JSON.stringify() 遇到 BigInt 会抛出错误:
"TypeError: Do not know how to serialize a BigInt"

在区块链、金融应用中,BigInt 是常见类型(如 wei、satoshi 等),必须正确处理。

测试 1: 表单序列化(包含 BigInt)

当前表单值:

tokenAmount:1234567890123456789012345678901234567890BigInt
gasLimit:21000BigInt
createdAt:Mon Jan 01 2024 00:00:00 GMT+0000 (Coordinated Universal Time)Date
username:aliceString

测试 2: 复杂嵌套对象

包含 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();