Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code:

 localStorage.setItem('someString', JSON.stringify(MyTypescriptObject));

This method stores the object as a plain string. For example:

 private _id: string;

 get id(): string {
   return this._id;
 }
 set id(value: string) {
   this._id = value;
 }

When retrieving the data using:

return <MyTypescriptObject>JSON.parse(localStorage.getItem('someString'));

The output is:

{_id: "1"...}

If Typescript is not compatible with local storage, it may not be worth using it. In fact, it could even mean having to rework all existing code to remove it completely.

Answer №1

Local storage is not the main concern here. You can store the class as data in JSON format and then restore it to a new instance of the class.

An easy way to do this is by adding a constructor that takes the JSON object and applies it to the class instance:

class MyTypescript {
    constructor()
    constructor(id: string, name: string)
    constructor(data: Partial<MyTypescript>)
    constructor() {

        if (arguments.length == 1) {
            let data = arguments[0];
            Object.assign(this, data);
            return
        }
        let id = arguments[0];
        let name = arguments[1];
        this._id = id;
        this._name = name;
    }

    public fromJson(data?: Partial<MyTypescript>) {
        var result = new MyTypescript();
        Object.assign(result, data);
        return result;
    }
    private _name: string;
    private _id: string;

    get id(): string {
    return this._id;
    }
    set id(value: string) {
    this._id = value;
    }
}

var obj = new MyTypescript();
obj.id = "10";
var data =  JSON.stringify(obj);
var obj2= new MyTypescript(JSON.parse(data));

If your goal is simply to hold some data in an object, using an interface might be a more suitable approach. In Typescript, declaring a class with properties for a basic data structure may be unnecessary. Instead, declare an interface and assign object literals to variables of that type, which will work seamlessly with JSON:

interface MyTypescript {
    id: string;
    name: string
}

var obj : MyTypescript = {
    id: "10",
    name: "foo"
};
var data = JSON.stringify(obj);
var obj2: MyTypescript = JSON.parse(data);

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

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...

The file type stored in Firebase storage is identified as 'octet-stream' rather than the expected 'png/jpg' format

I am experiencing an issue with uploading images to Firebase storage. After uploading them, I notice that they are labeled as application/octet-stream instead of the expected types like image/jpeg or image/png. Below is the code snippet I am using: <in ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...

Issue: Incomplete data retrieval using JS/React fetchDescription: I am facing

I am currently working on an app centered around the card game Magic. The concept involves pasting a list of cards into a textbox and then clicking a button to display corresponding card images. My approach entails using fetch requests to interact with an ...

How can you use jQuery to target a textbox based on its value that includes quotation marks?

Dealing with a JavaScript string that includes a quote mark can cause some difficulties. For example, strings like Don't click this checkbox or He said "hi" pose unique challenges when trying to find an exact match in a checkbox value. Consider the H ...

The HTML table inexplicably displays a random comma out of nowhere

When working on my HTML table, I noticed that it was rendering a comma unexpectedly. I am using Nodemailer and SMTP Google server, and I suspect the issue lies within the HTML code. However, I am struggling to identify the exact problem. https://i.stack.i ...

JavaScript error: Resource could not be loaded

When I have a js function called by an onclick event in a radio button, it doesn't work if the function is placed in the same ascx file where the radio button is defined. To resolve this issue, I moved the function to the ascx that includes the ascx w ...

The chosen options will automatically populate the text-boxes that require dynamic summation

I am encountering an issue with a select option that should dynamically populate specific values in text-boxes (different prices) based on the selected option. The goal is to sum up the values in the text-boxes and display the total in another text-box. Ho ...

Angular FormData causes Unexpected Token error when using HTTP Post

In my Ionic application, utilizing Angular and Capacitor, I have a function specifically designed for uploading files using FormData post method. var data = new FormData(); data.append(name, blobFile, "TestName"); data.app ...

Utilizing HTML5 canvas to extract pixel data from an image loaded from an external source

When it comes to security reasons, doing it directly may not be feasible. Nevertheless, there are rumors circulating about certain image-hosting platforms that permit the use of their images in a comparable way (could Google Picasa be one?). I might be mis ...

The conversion of the input (ImageButton) to jQuery is not possible

Within my gridview, I have ImageButtons that open an edit form. To determine the ID, I need to access the surrounding element (Row). The issue arises when I try to pass 'this' as a parameter in the onClientClick event which triggers a JavaScript ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Styling child elements in Angular using css from its parent element

I have a question: Regarding the structure below <component-parent> <first-child> <second-child> <third-child></third-child> </second-child> </first-child> </component-parent> Now I want t ...

Is it possible to save jQuery plugin initialization settings for future use?

Is it possible to save a default set of settings for a lightbox jQuery plugin, including options and callback functions, in a variable or array that can be referenced later in different contexts with varying configurations? For example, could I initially ...

Obtain the ClientID for a particular user control that is within a repeater's bindings

I have a collection of user controls that I am connecting to a repeater. The user control: (Example) "AppProduct" <div> <asp:Button ID="btn_details" runat="server" Text="Trigger" /> <asp:HiddenField ID="pid" ...

Is there a way to prevent the splash screen from appearing every time I navigate using a navbar link in a single page application (SPA)?

Recently, I came across this tutorial and followed it diligently. Everything seemed to be working perfectly until I encountered an issue with my navbar links. Each time I clicked on a link, the splash screen appeared, refreshing the page without directing ...

Using framer-motion with Next.JS ensures that content remains consistent during navigation

I added a Link on my homepage that connects to the About Us page: <Link href="/about"><a>About us</a></Link> In my _app.js file, there is an AnimatePresence wrapper: <AnimatePresence exitBeforeEnter> <Component {...p ...

The expected behavior is not displayed when using Async.waterfall within a promise queue

In our software implementation, we have utilized a promise queue feature using the q library. The sequence of functions is structured as follows: PQFn1 -(then)- PQFn2 - .... Within PQFn1, an array of values is passed to a callback function implemented wi ...

Using ngClass for conditional styling in Angular 7: A step-by-step guide

Utilizing multiple classes within Angular's [ngClass] functionality is my current challenge. The goal is to make it function based on the flag condition provided by the component.ts file. ...

Using Javascript and jQuery to validate strings within an array

My existing jQuery code works perfectly by returning true if it matches the specified name. jQuery(function($) { var strings = $(".user-nicename").text(); if (strings === "name1") { $('.mention-name').hide(); $('.se ...