Naresh
Naresh

Reputation: 25793

Serializing/Deserializing JSON to TypeScript with conversions

I am trying to serialize TypeScript objects to JSON and vice-versa. While converting, certain fields have to be transformed, e.g. Date objects to ISO 8601 strings, enumerations to values required by the wire format, etc. I am currently creating type definitions for both the TypeScript object and the JSON object (trying to avoid typing the JSON object as any). Is there a better pattern for doing 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";
}

Here's the code to serialize/deserialize + the type definitions for the two formats:

interface Person {
    name: string;
    title: string;
    dob: Date;
}

interface JsonPerson {
    name: string;
    title: string;
    dob: string; // 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
    }
}

Upvotes: 1

Views: 4267

Answers (1)

basarat
basarat

Reputation: 275967

The default Date.prototype.toJSON already uses the ISO string so you don't need to do dob.toISOString()

What you have is fine and generally what I prefer as well (explicit serialization / deserialization). I also have a video on the subject.

But if you want to use a serialization library here are two that I recommend for TypeScript that use decorators:

Upvotes: 2

Related Questions