How can one effectively incorporate a 'toJson' function in TypeScript?

Does anyone know the best approach for adding a toJson function to a custom class? I've considered implementing functions like Foo.toJson, Foo.toJsonObject, or Foo.jsonify.

Some examples suggest using a serializer. Is that necessary, or is there a more standard way of achieving this functionality?

I want to be able to use the following code:

const foo = new Foo();
fse.writeJson('file.json', foo);

Additionally, for database connection purposes, I also need to manually create a json representation:

const foo = new Foo();
db.writeObject(foo.toJson());

Answer №1

If you are unable to directly modify the original class, one way to accomplish this is by following these steps:

  1. Create a new data type that includes the toJSON method in addition to the properties of the original type
  2. Typecast the object to the newly created data type
  3. Assign the required toJSON method to the object

Here's an example demonstrating this concept:

class Bar {
    public number: number;

    constructor(number: number) {
        this.number = number;
    }

    display() {
        console.log(this.number);
    }
}

type ExtendedBar = Bar & {
    toJSON: () => string;
}

const y = new Bar(42);

(y as ExtendedBar).toJSON = function () {
     return `"Number(${this.number})"`
}

y.display();
console.log(y);

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

The specified container is not a valid DOM element

Recently, I decided to implement Redux into my React application. However, as I began setting everything up within my index.js file, I encountered an error message: https://i.sstatic.net/4kL2T.png. After some research, I learned that this error is related ...

Difficulty establishing a connection between NodeJS and Google Drive API

I am currently facing a challenge in my NodeJS application where I'm attempting to set up a gallery page. Despite having all the necessary configurations and connections with Google Drive API, something seems amiss when accessing the /gallery route. T ...

jQuery functions seamlessly on Chrome, Firefox, and Internet Explorer, unfortunately it does not work on iPhone

The code functions properly on desktop browsers, but encounters issues on iPhone devices. I would greatly appreciate it if you could take a look and help me identify the problem. What do you think could be causing this discrepancy? <ol style="margin: ...

An unexpected error occurred during page generation. Any relevant console logs will be shown in the browser's terminal window

Encountered a RangeError: Maximum call stack size exceeded while compiling this web app in the browser. The error occurred on my header tag and sometimes on the return tag. What should I do? export default function Header() { return ( <> ...

Can a client receive a response from server actions in Next.js 13?

I'm currently developing a Next.js application and I've created an action in app/actions/create-foo-action.js. In this server action, I am attempting to send a response back to the client. import { connectDB } from "@utils/database" imp ...

After installing the npm package, use browserify to bundle the bs58 library

I am trying to bundle the bs58 module using browserify by following the instructions provided on this website: npm install --save bs58 npm install -g browserify browserify < /mypath/lib/bs58.js > /mypath/lib/bs85.bundle.js In my HTML + JS file, I ...

What is preventing me from sending a POST request to my Node.js Express server?

Currently, my goal is to develop a straightforward user registration system. I simply wish to register through the HTML form and then be able to log it in the server using console.log. However, when attempting to achieve this with fetch, I encountered the ...

What is the solution to setting true and false equal to true in an AngularJS expression?

How can I determine if an input field has been touched and is empty, without using the built-in functions in Angular? <form-input is-invalid-on="isTouched && !gs.data.name || gs.data.name.length > 50"></form-input> If isTouched &am ...

React splits the page and interrupts the scroll event listener

For some reason, my webpage has been split by the React.js library. When attempting to scroll down while hovering over the top navigation menu, scrolling becomes impossible. However, scrolling works fine when done on any other part of the screen. I' ...

Clicking does not result in a change of the view

While experimenting with this code snippet : http://jsfiddle.net/9fR23/187/ Something seems off as the table elements are not being hidden when clicking on the "Flip!" div. The elements are supposed to be hidden based on the state change determined by th ...

I am experiencing difficulties with my data not reaching the function in my component.ts file within Angular

My current project involves integrating Google Firebase to handle the login functionality. I encountered an issue where the data inputted from the HTML page to the component.ts file was not being processed or reaching Firebase. However, when I initialized ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

Dynamic fields added using JavaScript are not recognized by PHP

I have a MySQL database where orders are stored along with various activities. My PHP/HTML page retrieves these activities when an order is clicked and allows users to modify them using a form. Upon submission, another PHP file updates the database by loop ...

Encountering an error while submitting form via Ajax to PHP backend

Currently, I am in the process of developing a form that solicits information from a user, including their name, address, amount1, amount2, and a comment. It seems that the radio inputs for amount1 and amount2 are causing issues with my form. Upon submiss ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

concerning a snippet of programming code

I'm new to coding and I'd like some help understanding this piece of code, particularly the red colored fonts. Which page value are they referring to? $(function() { $("#title").blur(function() { QuestionSuggestions(); }); }); funct ...

A guide on utilizing URL parameters in Express.js to deliver images as static files

Looking to dynamically serve images from an "images" directory in my project based on user input, how can I achieve this? For instance, https://localhost:3000/images?fileName=burger This URL should display the corresponding image in the browser. If any ...

A guide on resolving the 'Unexpected identifier array in JSON Parse Error' encountered during an AJAX Request

I'm currently working on setting up a Contact Form Validation and I require the variable $msg from a php script called 'sendEmail.php'. The actual mailing system is functional, as the script successfully receives form inputs from index.php a ...

In need of assistance with posting data on a Captive Portal using Ruckus AccessPoint Javascript

We are currently working on implementing a captive portal using Ruckus AP for our guests. Our setup includes a form where users can input their username and password. Upon clicking "Login", we aim to post this data to the Ruckus AP's user_login_auth. ...

JavaScript: The Battle of Anonymity - Anonymous Functions vs Helper

I'm currently grappling with a piece of functional style code that is featured in the book Eloquent Javascript: Here's the issue I'm facing: When I have the count() function passing an anonymous function to reduce(), everything seems to wor ...