Serialising and deserialising TypeScript types in local storage

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

Answer №1

1) TypeScript offers optional typing, allowing developers to work around the strictness of its type system. The use of the any type enables dynamic typing, which can be useful when used correctly but also risky if not handled carefully.

For example, the following code will compile:

var x: string = <any> 1;

In this scenario, the number 1 is casted as any, indicating to TypeScript that the developer knows how to handle it. Even though assigning any to a string may lead to errors during runtime, TypeScript allows it due to its design philosophy of types existing only at compile time.

When it comes to serializing and deserializing data, using JSON.stringify and JSON.parse may not always suffice. Type information can be lost during these processes, leading to potential discrepancies between in-memory storage and transfer/storage requirements.

It is recommended to define interfaces for objects to be saved, create a .toJson method on model objects for serialization, and utilize factory functions or constructors for deserialization. This approach provides more control over data storage and helps prevent deserialization issues.

Best of luck with your coding endeavors!

Answer №2

If you want to transform the string back into a moment, consider utilizing the reviver functionality of JSON.parse:

JSON.parse(input, (key, value) => {
  if (key == "date") {
    return parseStringAsMoment(value);
  } else {
    return value;
});

However, keep in mind that browser support for reviver may vary from basic JSON.parse.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bringing in personalized data types using unique import aliases

Recently, I made changes to my Next.js project by upgrading it to TypeScript. One of the modifications I made was updating my import alias from @/* to @*. Below is the new configuration in my tsconfig.json. { "compilerOptions": { "targ ...

What is the best method to handle errors when retrieving JSON data and updating it using fetch()?

I need to figure out a way for the setMessage not to appear when encountering a PUT ERROR 404 not found in the updateTemplate function. I attempted using catch(err) but was unsuccessful. Here is the complete code snippet: My unique version of the code... ...

Using type conversion dynamically within a select query

I have completely revised my question due to an inaccurate description of the issue! We need to store a wide range of information about a specific region in a data structure that allows for flexibility without limiting user possibilities. To achieve this ...

The guide to integrating the npm package 'mysql-import' into a node.js project with TypeScript

I'm currently facing an issue while trying to import a dump to a database using node.js and the npm module 'mysql-import'. Initially, I wrote the code in JavaScript and it worked flawlessly. However, when I attempted to modify it for TypeScr ...

Sequelize Error: Unable to access properties of an undefined object (reading 'replace')

An error occurred while attempting to create a new table. The specific error message is as follows: D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\utils.js:364 return s.replace(new RegExp(tickChar ...

Extending the type of parameters in TypeScript

I am trying to call a function from my UI library with a parameter type that extends the original (Suggestion) type by adding more properties. I found a resource that suggests it is possible here: https://github.com/Microsoft/TypeScript/issues/2225 (in the ...

What is the best way to decipher JSON using Java?

Currently in the midst of developing an Android test app that requires JSON test data parsing. The structure of the JSON data is as follows: {"id":1,"name":"Test Test","questions":[{"id":1,"test":1,"text":"Can you answer this question?","answers":[{"id": ...

Using TypeScript to apply a typed decorator function to a subclass

I've taken on the challenge of creating a node.js and MongoDB ORM library similar to "Entity Framework" using TypeScript. This library will allow users to define a Model class (e.g. Person) that extends a Base class. The class decorator will enhance ...

Encountering a promise error when using TypeScript and React Lazy

I've been working with React and TypeScript, incorporating a higher order component to verify user authentication. However, after implementing the hoc, I encountered an error in my routes: /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/rem ...

Perform a script to handle the escaping of quotation marks within a value

My goal is to create a key/value pair in local storage. Here's what I have been trying: browser.executeScript('localStorage.setItem("groups", "[test]");'); After executing the code above, I receive [test] as the value. However, my desired ...

Establish a connection between MongoDB and the built-in API in Next.js

I've been working on integrating a MongoDB database with the Next.js built-in API by using the code snippet below, which I found online. /api/blogs/[slug].ts import type { NextApiRequest, NextApiResponse } from 'next' import { connectToData ...

What is the process for importing components from a Stencil library into a React application?

After successfully creating: a stencilJS component library named "my-lib" using the "npm init stencil" wizard and an Ionic React app using "ionic start myApp tabs" I am now trying to incorporate the default "my-component," aka MyComponent from my-lib. H ...

The PHP script is utilizing jQuery to interact with data,

Recently, I have been working on some PHP code that returns JSON data. However, I encountered an issue with extracting values for "OK" due to the format. In order to get the values, I had to use a jQuery trick which seemed messy and not ideal. Any suggesti ...

Guide to serializing and deserializing an ArrayList, including properties of an Object datatype

Is there a way to maintain the object types during the deserialization of a json object? I've noticed that the ArrayList is lost and ends up as an object array, while the rectangle is completely gone. Edit: Unfortunately, I am unable to adjust the ob ...

Ways to relay messages from `Outlet` to web pages

My Layout.tsx: import { FC, useState } from 'react'; import * as React from 'react'; import { Outlet } from 'react-router-dom'; export const Layout: FC = () => { const [username, setUsername] = useState('John') ...

What is the method for configuring an ExtJS JsonStore to insert the JSON data directly into the request body?

My JsonStore setup is like this: var store = new Ext.data.JsonStore({ restful: true, url: '/categories', remoteSort: true, idProperty: 'Id', totalProperty: 'total', root: 'results', write ...

What could be causing the 404 error when trying to make a get-request to fetch a list of all users?

Having trouble retrieving a list of users using my endpoint, as it keeps returning a 404 error. I have set up a model, controller, router, and index file for the user in my application. Below is the User.ts model: import { Schema } from 'mongoose&apo ...

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

What is the reason behind Angular's renderer.listen() causing the text to be deselected?

(Background: my project involves developing an email processor that displays emails on a web page) To enable click events in a specific area, I leverage Angular's Renderer2. This approach is necessary because the content is dynamically generated with ...