Naming convention for TypeScript accessors

Expanding on the previous solution

When I convert the example object to JSON from the answer above:

JSON.stringify(obj)

The output is:

{"_id":"3457"}

If I intend to transmit this data over a service and store it in a database, I prefer not to use the field name '_id'. Doing multiple translations on field names during storage is not ideal.

My question is, what would be a suitable naming convention for accessors to achieve better property names without compromising the accessor shortcut?

For instance:

private id: number;

public get g_id(): number {
    return this.id;
}

public set s_id(value: number) {
    this.id = value;
}

Answer №1

There are a couple of solutions that come to mind:

  1. Instead of relying on JSON.stringify, consider creating your own function to handle field name translations. For example:

    public customStringify(): string {
        return JSON.stringify({username: this._username});
    }
    

    If you prefer not to manually rename each field, you could potentially write logic that iterates over Object.keys(this).

  2. To avoid conflicts between accessors and actual fields, you can store the actual data in a separate object and then apply JSON.stringify to that object.

Answer №2

Type-Aware JSON Parser & Serializer

I was introduced to this library by @devzero in response to a previous question of mine, and I have been extremely impressed with its performance so far.

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

Storing the subscription value retrieved from an API in a global variable

I am trying to find a way to make the data retrieved from an API accessible as a global variable in Typescript. I know that using subscribe() prevents this, so I'm looking for a workaround. Here is the API code: getResultCount(category:any):Obs ...

Exploring the Issue with SWR Hook in Next.js using TypeScript

Seeking assistance with the SWR hook as I navigate through some challenges while attempting to use it effectively. This time, the issue appears to be minor. The objective is to set a breakpoint in my API to retrieve data, using axios. The problem arises ...

Learn the method for triggering events with a strongly-typed payload in Vue 3 Composition API and TypeScript

I'm currently exploring Vue 3 Composition API along with TypeScript, particularly focusing on emitting events with a strictly typed payload. There's an example provided below, but I'm unsure if it's the most effective way to achieve t ...

Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code: import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; import {Observable} from 'rxjs' ...

Can TypeScript be used to generate a union type that includes all the literal values from an input string array?

Is it feasible to create a function in TypeScript that takes an array of strings and returns a string union? Consider the following example function: function myfn(strs: string[]) { return strs[0]; } If I use this function like: myfn(['a', &a ...

Protractor for Angular 2: Pausing execution until specified element obtains a specified class

Looking for a method to delay my e2e test (angular2 project) until the targeted element receives a specific css class. Is there an alternative approach without using browser.wait() or browser.sleep()? ...

Is it possible to utilize [key:string]: any in order to eliminate the requirement for an additional function when working

Currently, I am utilizing recompose within my React project. Specifically, I am leveraging its compose function which is defined as: function compose<TInner, TOutter>( ...functions: Function[] ): ComponentEnhancer<TInner, TOutter>; interf ...

What is the best way to create a universal function that can return a promise while also passing along event

I created a specialized function that waits for an "EventEmitter" (although it's not completely accurate as I want to use it on other classes that have once but don't inherit from EventEmitter): export function waitEvent(emitter: { once: Function ...

The database did not respond, causing the API to resolve without sending a response for the specified endpoint (/api/dates). This could potentially lead to requests becoming stalled in Next

I have been attempting to retrieve a list of dates from my database in a straightforward manner, but unfortunately, I am not receiving any response (even after trying to log the response data to the console). The only feedback I seem to be getting when sel ...

Step-by-step guide on adding a command to a submenu through the vscode extension api

I'm developing a Visual Studio Code extension and I want to include a command in a submenu like this https://i.stack.imgur.com/VOikx.png In this scenario, the "Peek" submenu contains commands such as "Peek Call Hierarchy". My current Package.json fi ...

Adjust Column Title in Table

Is it possible to customize the column headers in a mat-table and save the updated value in a variable? I've been looking for a solution to this but haven't found one yet. ...

Generate a fresh array by filtering objects based on their unique IDs using Angular/Typescript

Hey there, I am receiving responses from 2 different API calls. Initially, I make a call to the first API and get the following response: The first response retrieved from the initial API call is as follows: dataName = [ { "id": "1", ...

When using `onClick` in React, the old state value is not captured even though it may appear to be

In order to enhance the modularity and generality of my tabs and tab slots, I have developed a somewhat intricate setup. To achieve this, I opted to create a context and provider that expose methods for manipulating tabs and slots (where slots represent wh ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

Angular Form: displaying multiple hashtags within an input field

Utilizing Angular CLI and Angular Material, I have created a form to input new hashtags. I am facing difficulty in displaying previously added hashtags in the input field. Below is the code I have written: form.component.html <form [formGroup]="crea ...

Zod data structure featuring optional fields

Is there a more efficient way to define a Zod schema with nullable properties without repeating the nullable() method for each property? Currently, I have defined it as shown below: const MyObjectSchema = z .object({ p1: z.string().nullable(), p2 ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

Steps for managing files in Ionic Native: creating, reading, and writing them

Struggling to find proper examples for file operations like creating, reading, and writing text or logs into a file? I've done a lot of research but haven't stumbled upon any suitable solutions. The examples provided in this link seem helpful, ho ...

Unit testing the error function within the subscribe method in Angular

I've been working on a unit test for the subscribe call, but I'm struggling to cover the error handling aspect of the subscribe method. The handleError function deals with statusCode=403 errors and other status codes. Any assistance would be grea ...

Prevent the event listener from continuously triggering

I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again. The problem arises when this event is ...