Converting string literals to an array of enums

I have a scenario where I am getting the following data in an API response:

{ "roles": [ "ADMIN", "USER" ] }

The response always includes an array of roles (USER, PRESENTER, ORGANIZER, and ADMIN).

I am looking to transform this into a valid TypeScript array (Role[]), where the type Role is defined as:

export type Role = 'USER' | 'PRESENTER' | 'ORGANIZER' | 'ADMIN'

Do you have any suggestions on how to achieve this?

Answer №1

Your Position data type is not classified as an enum, but rather a string type with restricted values.

To satisfy TypeScript, you can simply cast the output as a Position[], assuming the input data is always valid!

const info: {positions: Position[]} = JSON.parse('{"positions": ["MANAGER", "EMPLOYEE"]}');
info.positions // TypeScript will recognize it as a Position[]

Answer №2

If you wish to convert it to your union type, follow this method:

const apiRoleArray = ["ADMIN", "USER"];
const realRoleArray: Role[] = <Role[]>apiRoleArray;

However, it is advisable to validate its contents rather than solely relying on the API. :-) Utilizing the insight provided in this question's responses, you can define the type by referencing the keys of an object instead of explicitly declaring it (refer to the accepted solution there for clarification):

const roleStrings = {
    USER: "",
    PRESENTER: "",
    ORGANIZER: "",
    ADMIN: ""
};

export type Role = keyof typeof roleStrings;

Establish a validation function as follows:

const isRole = (s: string): s is Role => {
    return roleStrings.hasOwnProperty(s);
};

Then create a robust conversion function, such as:

const rawToRoleArray = (rawArray: string[]): Role[] => {
    return rawArray.map(s => {
        if (!isRole(s)) {
            throw new Error("Invalid Role: " + s);
        }
        return <Role>s;
    });
};

(you can combine these functions if needed)

Finally, put them into action:

// Valid
const realRoleArray: Role[] = rawToRoleArray(["ADMIN", "USER"]); 
console.log(realRoleArray);
// Invalid
const realRoleArray2: Role[] = rawToRoleArray(["ADMIN", "FOO"]); 
console.log(realRoleArray2);

Try it out in the playground | Test it on jsFiddle

Answer №3

It seems like that is your desired course of action.

enum RoleEnum {
  USER,
  PRESENTER,
  ORGANIZER,
  ADMIN
}

const parseEnum = (name: String): RoleEnum  => RoleEnum[`${name}`]

const parsed: RoleEnum[] = [ 'ADMIN', 'USER' ].map(parseEnum)

console.log(parsed)

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

Leverage TypeScript to access custom component properties and URL parameters from react-router-dom

In my react-router-dom setup, I have a route structured like this: <Route path="/result/:result" component={ResultsView} audio={audio} speechRecognition={speechRecognition} /> Furthermore, I have a component with specified props as follows ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

Solution for repairing the display location button on Android within a React Native Map

I am facing an issue with the Location Button in my React Native Maps app. When the app is opened for the first time and the map is rendered, the button disappears. However, if I close the app but leave it running in the background, upon reopening the app, ...

Working with JSON object values in a Spring Boot application

Here is a sample JSON data: [{"state":"Completed","mignum":146289,"projectleader":"Eric Lok","productiondate":"Jun 6, 2018","installationtiers":"Windows Server","targetplatform":"Production","apprelated":"UPS Pickup Point Web Application","appversion":"2. ...

Exploring the world of reactive programming in JavaScript by transforming traditional AJAX calls into Bacon.js streams while incorporating

How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination? With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to popul ...

Will the bootstrap carousel continue running in the background even if I hide it?

Currently, I have incorporated the twitter bootstrap carousel into my website with the following code: <div id="slider" class="carousel slide"> <!-- Wrapper for slides --> <div class="caro ...

Converting JSON data to a different format using SwiftJSON

I am currently facing an issue with obtaining JSON data from web services using Alamofire + SwiftJSON as I am unable to convert the type JSON to another type. Here is an excerpt of my code: var product:JSON = [] override func viewDidLoad() { Alamof ...

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

Guide on how to bundle a TypeScript project into a single JavaScript file for smooth browser integration

I am currently working on a small project that requires me to write a JavaScript SDK. My initial plan was to create a TypeScript project and compile it into a single JavaScript file, allowing users of my SDK to easily inject that file into their web pages. ...

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

Understanding the proper way to enclose JSX components and exhibit JSON based on user input

I'm currently working on a university administration website using React that needs to support multiple languages. I have successfully built the Login page, which you can see here: https://i.stack.imgur.com/cIiaU.png Now, my next task is to allow us ...

What could be causing Vue to not fully parse the JSON object that I am sending from PHP as a prop?

My current challenge involves passing a JSON object as a prop into a Vue component. The JSON object is generated using the `json_encode()` function on a WordPress query that retrieves all posts for the page. To ensure proper formatting, I am also employing ...

The Nodejs function exits before the internal function finishes executing

Currently, I am facing an issue where despite MongoDB returning the correct number of users (more than 0) when running console.log within collection.find(), the function userExists always returns false (0). I'm seeking guidance on how to ensure that ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

What is the best way to convert JSON data from PHP into a ListView on an Android app?

Greetings! I am a novice programmer seeking assistance with parsing the following output into my Android listview. I have utilized PHP connected to MySQL to generate this data : {"id":"2","name":"Username : garrett","password":"Password : important"}{"id" ...

Is it possible for me to identify the original state of a checkbox when the page first loaded, or the value it was reset to when `reset()` was

When a webpage is loaded, various input elements can be initialized as they are declared in the HTML. If the user modifies some of the input values and then resets the form using reset(), the form goes back to its initially loaded state. I'm curious, ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

Can you explain the distinction between JSON syntax and object assignment in programming?

While exploring the Twitter Client example on Knockoutjs, one may notice that some properties are included in the JSON object while others are assigned outside of it. What distinguishes these two approaches? And why can't methods such as findSavedList ...

Analyze the value of key.name against a string within a JSON reply

Below is the JSON data I am working with: { "value": [ { "id": "/subscriptions/5a9c0639-4045-4c23-8418-fc091e8d1e31/resourceGroups/citrix-xd-0ec69105-c451-4676-8723-97932bf4d94a-ayjzs", "name": "citrix-xd-0ec69105-c451- ...

The error message "404 Not found" is returned when attempting to retrieve a Google spreadsheet

I have exhausted all of my options on the web trying to retrieve my Google spreadsheet as a json file. $.getJSON() However, I am constantly receiving a 404 Not Found error. When I publish to the web, the URL I get is: https://docs.google.com/spreadsheets ...