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

An issue arose during the installation of the package 'npm i angularfire2'

I am currently working on an Angular project and I am trying to import AngularFireStorage using the following line of code: import { AngularFireStorage } from 'angularfire2/storage'; I attempted to do this by running the command npm i angularfire ...

Include your comment within the "manifest.json" file

Planning to create a chrome extension, I realized I needed to include manifest.json, but unfortunately, the IDE doesn't seem to pick up on comments. According to the documentation: Manifest.json is a JSON-formatted file, with the exception that it ...

Utilizing the subclass type as a parameter in inheritance

Looking for a way to restrict a function in C# to only accept classes of a specific base class type? In my current implementation, I have a base class (which can also be an interface) and n-classes that extend it. Here is what I am currently doing: abstr ...

Is it possible to add additional text to an input field without modifying its existing value?

I have a numerical input field labeled "days" that I want to add the text " days" to without altering the actual numerical value displayed. <input type="number" class="days" (keyup)="valueChanged($event)"/> Users should only be able to edit the num ...

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

Error in Typescript SPFx: The property 'news' is not found in the type 'Readonly<{}>'

Currently, I am working on developing a spfx react component to showcase an RSS feed in the browser. My prototype is functional in a test environment, however, as spfx utilizes TypeScript, I am encountering a type error that I am unsure how to resolve. Rs ...

Transferring JSON data back and forth between C# and PHP files

I am trying to send a JSON request from C# to a PHP file in order to save data into a text file. However, the PHP file is unable to read the data. Below is my code: User user = new User { id = 1, name = "Bob", address = "password", phone = "0111111111", a ...

Form control identifier and input field name

I am currently developing a custom input feature for my application. One of the functionalities I want to include is auto-completion, and in my research, I found out that certain conditions need to be met for it to work: In order to enable auto-completi ...

Is it possible to use ng-bootstrap with vertical tabs?

I'm experimenting with displaying ng-Bootstrap tabs vertically, but the provided example doesn't quite fit my needs. I'm envisioning a layout similar to what I've sketched in the diagram. Do you think it's achievable? Any suggestio ...

What is the best way to assign a default value in mat-select when using an ngFor loop?

Is there a different approach to setting a default value in mat-select within an *ngFor loop? I'm having trouble accessing the element in the array from the loop as desired. .ts file: persons: Person[] = .. //consist of Person with name and age .htm ...

Error message: "Encountered 'Cannot Get' error while building Angular

I encountered an error when trying to run my Angular project in IntelliJ. Upon opening the browser on localhost, I received the message Cannot GET / Here are the steps I followed: Opened up the project Ran npm install -g @angular/cli@latest Ran gradlew c ...

What is the best way to retrieve organized data from a mat-table spanning multiple pages?

Is there a way to extract sorted data from the dataSource of a mat-table and save it as sortedData in order to export it to a CSV file? The dataSource has filters and pagination applied through this.dataSource.filterPredicate; this.dataSource.paginator = t ...

The Angular dependency provider is failing to supply the requested alternative class

I am currently in the process of writing unit tests for the doc-manager.component component. This particular component relies on the DocService, but I want to swap it with instances of MockedDocService within my tests. By leveraging alternative class prov ...

Postman - Setting up dynamic variables using response data

Like many of you, I am always looking for ways to simplify my work :) The issue at hand is whether it is feasible to establish a variable in Postman based on the response value from my application backend. Here's the rundown: My application generate ...

Is it possible for Angular to handle multiple routes for one path?

To create a landing page for anonymous users and an inbox for authenticated users without relying on manual navigation or path changes, I attempted to set up multiple components associated with the root path. However, my routing block did not work as plann ...

Experiencing an issue with mui/material grid causing errors

An error occurred in the file Grid2.js within node_modules/@mui/material/Unstable_Grid2. The export 'createGrid' (imported as 'createGrid2') could not be found in '@mui/system/Unstable_Grid' as the module has no exports. Desp ...

Advantages of optimizing NodeJS/TypeScript application by bundling it with webpack

Currently, I am working on a Node/Express application and I am interested in incorporating the most recent technologies. This includes using TypeScript with node/Express along with webpack. I have a question: What advantages come with utilizing webpack t ...

Tips on passing an object as data through Angular router navigation:

I currently have a similar route set up: this.router.navigate(["/menu/extra-hour/extra-hours/observations/", id]) The navigation is working fine, but I would like to pass the entire data object to the screen in order to render it using the route. How can ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

By harnessing a JSON response

After sending an ajax request, the server's response is as follows: {"error":false,"success":true} The ajax code used: $.ajax({ url: '/update', type: 'post', data: $(this).serialize(), success: function(response) ...