Managing enum types with json2typescript

After receiving a JSON response from the back-end that includes an Enum type, I need to deserialize it. The JSON looks like this:

{
...,
pst:['SMS','EMAIL'],
...
}

In Typescript, I have defined my enum class as follows:

export enum PostSynchroActions {
  SMS = 'SMS',
  Email = 'Email',
  SocialWall = 'SocialWall',
  Transformation = 'Transformation',
  Clone = 'Clone'
}

I am looking to use the json2Typescript library for deserialization. How can I achieve this?

Below is an excerpt of my Typescript class used for deserializing the back-end JSON data:

export class Terminal { ...

@JsonProperty('pst',[PostSynchroActions]) actionPostSynchro:PostSynchroActions[] = [];

...

}

Answer №1

If you are sending keys, utilize PostSynchroActions[data]; otherwise, simply use data as PostSynchroActions. It's important to ensure that EMAIL matches Email, so the complete function should look like this:

export enum PostSynchroActions {
  SMS = 'SMS',
  Email = 'Email',
  SocialWall = 'SocialWall',
  Transformation = 'Transformation',
  Clone = 'Clone'
}

function postSynchroActionsFromKeys(data: string) {
    if(data === "EMAIL") {
        data = "Email";
    }
    return PostSynchroActions[data as PostSynchroActions] as PostSynchroActions;
}
function postSynchroActionsFromValues(data: string) {
    if(data === "EMAIL") {
        data = "Email";
    }
    return data as PostSynchroActions;
}

Playground

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

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...

After a specified number of attempts, confirm that the value has not been found

I am attempting to develop a script that will monitor a text file for the presence of names after a certain number of attempts. Currently, I have successfully created a script that reads a text file containing data in JSON format. I have also included a c ...

Is it possible for OpenFin to store logs in a secure database and what is the process for accessing logs located at %LocalAppData%openfinapps<app>app.log

System Information Here are the details of the system setup: OpenFin Process Manager Version: RVM = 8.1.0.4 Node.js: v16.15.0 Windows 10 Angular Application with C# .NET backend Issue: The current setup saves all application logs locally on users' ...

Using Angular to make an HTTP POST request to fetch data

My trusty .net backpack has been working flawlessly. However, I encountered an issue when trying to connect it with the Angular front end. All backend requests are post requests and require passing an ApiKey in the body of each request. Interestingly, ever ...

Effortlessly sending information to the Material UI 'Table' element within a ReactJS application

I have integrated a materialUI built-in component to display data on my website. While the code closely resembles examples from the MaterialUI API site, I have customized it for my specific use case with five labeled columns. You can view my code below: h ...

I am constantly facing the same frustrating error in every meanstack project I work on: Failed to load resource: net::ERR_CONNECTION_REFUSED. Can't seem

I've been diving into educational resources to learn how to build meanstack applications with basic CRUD capabilities. After downloading various projects from Github and setting up the necessary modules, I encounter a consistent error when running the ...

What is the most efficient way to modify a list within another list variable in Angular without impacting the parent list?

Here is a data list that I am working with: subscriberDataList -> wipEligibilityList -> dependentList dependentList -> wipEligibilityList -> eligibilityList wipEligibilityList[0] -> status - ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

Struggle between Angular and fundamental CSS principles

Upon following the steps below, I aim to achieve my desired grids: How to set auto-margin boxes in flexible-width design using CSS? The solution provided is effective when implemented outside of Angular. However, when inserted inside an Angular component ...

NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar. Essentially, I need to s ...

Step-by-step guide to troubleshoot and resolve nodeJS PUT route issue when updating an incorrect ID

Attempting to update an object with the wrong ID using the PUT route. I attempted to switch from params.id to body.id, but it didn't alter the output as expected. The update is only affecting the first object ever created, which does not correspond t ...

Get ready for transitioning with a cell that is populated by JSON data

When populating a UITableViewCell with JSON data, I am using the following method: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdent ...

Troubleshooting the issue of "_this is undefined" in Angular 4

connect=()=>{ this.api=new trovaSDK_Init("normal",this.businessKey,"user","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="364345534476515b575f5f1e19565d">[email protected]</a>","","","",this.apiCallBack,thi ...

Removing background from a custom button component in the Ionic 2 navbar

Q) Can someone help me troubleshoot the custom component below to make it resemble a plus sign, inheriting styling from the <ion-buttons> directive? In my navbar, I've included a custom component: <notifications-bell></notifications-be ...

Adjusting the axis to maintain readability in vega-lite

In order to display a bar plot of measures where some values are significantly higher than others, I attempted to use a log scale and implement an outlier filtering step before plotting. I also wanted to try using an axis break to hide a large chunk of y ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

Ignore any information in NestJS that is not included in the data transfer object

In my NestJS controller, I have defined a route for updating locality information. The structure of the controller method is as follows: @Put('/:id') updateLocalityInfo( @Query('type') type: string, @Body() data: EditLocalityD ...

A guide on reading an external JSON file using React

I'm trying to integrate an external JSON file into my React app. To demonstrate what I'm aiming for, I've provided a functional example on Codesandbox.io: https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js Currently, the example ...