I'm currently working on a Typescript application where I store objects using local storage for development purposes. However, I've run into some trouble with deserialization.
Specifically, I have an object called meeting of type MeetingModel:
export interface MeetingModel {
date: moment.Moment; // using the library momentjs
}
In order to store this object in local storage, I use JSON.stringify(meeting)
.
I assumed that the stringify call would utilize moment.toJson(), which returns an iso string. This results in the value being stored as:
{"date":"2016-12-26T15:03:54.586Z"}
.
However, when I retrieve this object and attempt to parse it, I encounter an issue:
const stored = window.localStorage.getItem("meeting");
const meeting: MeetingModel = JSON.parse(stored);
The problem is that meeting.date now contains a string instead of a Moment object!
Firstly, I find myself questioning why TypeScript allows me to assign a string value instead of a Moment and why the compiler doesn't catch this error?
Secondly, I'm looking for a solution to convert plain JSON objects (aka strings) back into Typescript types.
While I can create a factory function to handle this conversion, it will become cumbersome as my object database grows.
Is there a more efficient way to handle storing objects in local storage while still maintaining their original data types?
Thank you