Skip to Content

Supported Types

CodableJSON automatically handles JavaScript types that standard JSON cannot serialize. Here’s a comprehensive table of supported types and their encoded formats:

Built-in Types

JavaScript TypeExample
Date{ $$Date: "2025-01-01T00:00:00.000Z" }
BigInt{ $$BigInt: "1234567890123456789" }
Set{ $$Set: ["a", "b", "c"] }
Map{ $$Map: [["key", "value"]] }
RegExp{ $$RegExp: "/hello/gi" }
Symbol{ $$Symbol: "test" }
URL{ $$URL: "https://example.com/" }
URLSearchParams{ $$URLSearchParams: "a=1&b=2" }
ErrorSee examples below
undefined"$$undefined"
Typed Arrays{ $$uint8array: [1, 2, 3] }
Special Numbers"$$NaN", "$$Infinity", "$$-Infinity", "$$-0"

Examples

Error Objects

Errors with simple messages are encoded concisely:

const error = new Error("Something went wrong"); encode(error); // { $$Error: "Something went wrong" }

Errors with additional properties preserve all information:

const error = new Error("Database connection failed", { cause: new Error("Network timeout") }); error.name = "DatabaseError"; error.code = "DB_CONNECTION_FAILED"; encode(error); // { // $$Error: { // message: "Database connection failed", // name: "DatabaseError", // cause: { $$Error: "Network timeout" }, // properties: { code: "DB_CONNECTION_FAILED" } // } // }

By default, the error stack is not included in the encoded output. You can include it by passing includeErrorStack: true to the encode function.

const error = new Error("Something went wrong"); encode(error, { includeErrorStack: true }); // { $$Error: { message: "Something went wrong", stack: "Error: Something went wrong\n at <anonymous>:1:1" } } const decodedError = decode<typeof error>(encoded); decodedError.stack === error.stack; // true, stack is preserved

Regular Expressions

const regex = /hello/gi; encode(regex); // { $$RegExp: "/hello/gi" } const simpleRegex = /test/; encode(simpleRegex); // { $$RegExp: "test" }

Typed Arrays

const uint8Array = new Uint8Array([1, 2, 3]); encode(uint8Array); // { $$Uint8Array: [1, 2, 3] } const float64Array = new Float64Array([NaN, 0, Infinity]); encode(float64Array); // { // $$Float64Array: ["$$NaN", 0, "$$Infinity"]

Special Numbers

encode(NaN); // "$$NaN" } encode(Infinity); // "$$Infinity" encode(-Infinity); // "$$-Infinity" encode(-0); // "$$-0"

Format Safety

CodableJSON automatically handles cases where your data conflicts with the internal format by escaping:

const data = { $$Set: [1, 2, 3] }; // This would conflict with Set encoding encode(data); // { "~$$Set": [1, 2, 3] } - automatically escaped const decoded = decode(encoded); // decoded.$$Set === [1, 2, 3] - correctly restored

The ~ prefix indicates escaped format keys. CodableJSON handles this automatically during encoding and decoding.

Last updated on