1

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
    }
}
1
  • 1
    I would think you'd only need the deserialization code, since serialization should just be JSON.stringify(Person)... Commented May 14, 2020 at 0:00

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the confirmation, Basarat, and nice video on this subject! BTW, I am also a fan of MobX and in fact have have written a router based on it: nareshbhatia.github.io/mobx-state-router
Just confirming, while automatic serialization of dates works, automatic deserialization of strings to dates will not happen, correct? I will need the new Date(dob) during deserialization.
` automatic deserialization of strings to dates will not happen, correct? I will need the new Date(dob) during deserialization` Correct 🌹

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.