I'm currently working on serializing TypeScript objects to JSON and vice versa. During this process, certain fields need to be transformed, such as converting `Date` objects to ISO 8601 strings and mapping enumerations to values required by the wire format. I am in the process of defining type definitions for both the TypeScript object and the JSON object in order to avoid using `any`. Are there any alternative patterns or best practices for achieving this?
Example
TypeScript Object:
{
name: 'John Smith',
title: 'Sr. Developer',
dob: new Date('1990-05-01T09:00:00Z');
}
JSON Object:
{
"name": "John Smith",
"title": "Sr. Developer",
"dob": "1990-05-01T09:00:00Z";
}
Below is the code snippet for serialization/deserialization along with the type definitions for the two formats:
interface Person {
name: string;
title: string;
dob: Date;
}
interface JsonPerson {
name: string;
title: string;
dob: string; // In ISO 8601 format
}
function serialize(person: Person): JsonPerson {
const { dob, ...rest } = person;
return {
dob: dob.toISOString(),
...rest
}
}
function deserialize(jsonPerson: JsonPerson): Person {
const { dob, ...rest } = jsonPerson;
return {
dob: new Date(dob),
...rest
}
}