The utilization of a JSON file string to define enum types results in an error stating that the type 'string' cannot be assigned to the type 'number' as mandated for calculated enum member values

In my code, I define an enum like this:

export enum AccountSettings {
  accountManagement = "Account management",
  managementOfRelatives = 'Management of relatives',
}

Next, I have a file named en.json, which contains the corresponding data for my enum values

{
  "account_management": "Account management",
  "management_of_relatives": "Management of relatives",
}

But when I try to use this data in my enum definition, I encounter an error:

import en from './en.json';

export enum AccountSettings {
  accountManagement = en.account_management, // displays Type 'string' is not assignable to type 'number'
  managementOfRelatives = 'Management of relatives',
}

I'm looking for a solution on how to successfully incorporate the data from en.json into my enum. Can anyone help with this?

Answer №1

Regrettably, you are faced with two consecutive challenges:

  1. The JSON content being imported is interpreted by TypeScript in a standard manner, treating the property value as a string. If this was within a .ts file, an as const assertion could have been utilized to make the entire structure readonly and allow TS to infer literal values. Unfortunately, this approach is not viable for files imported from JSON sources, as discussed in ms/TS#32063

  2. Even when dealing with a .ts file, TypeScript only recognizes a literal string value as a string enum representation if defined very simply, such as directly within a const variable; any slight complexity (even in a readonly object) will lead to a rejection by TS, triggering the same error message:

const foo = "bar"
//    ^? "bar" literal string

enum EnumFoo {
    Foo = foo // Accepted
}

const fooObj = {
    foo
    //^? "bar"
} as const // const assertion

enum EnumFooObj {
    Foo = fooObj.foo // Error
}

const bar = fooObj.foo
//    ^? "bar"

enum EnumBar {
    Foo = bar // Error
}

Interactive Demo Link

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

Ways to dynamically manipulate HTML elements in Angular 5

Recently, I've been attempting to programmatically transform an HTML element. Strangely, when I update the transform value in the console tab, it changes successfully, but for some reason it doesn't reflect in the element tab of the browser. onD ...

Using JavaScript to showcase a variety of colors in a dropdown menu control

I want to create a dropdown menu that displays different colors using JavaScript. Currently, I have implemented it in a way that changes the background color based on the color selected from the dropdown. Here is my code: <select id="colorSelect" clas ...

Is there a way to activate the final form when submitted?

I am facing an issue with React Final Form. Despite following the example in the official documentation, I am still struggling to understand why my form is not triggering the onSubmit function as in the example. I am also grappling with understanding the p ...

Table order is requested, but the index fails to comply

I am facing an issue with sorting and deleting data from a JSON table. Even after sorting the columns, clicking "Delete" removes the wrong entry because the $index is not updated properly. Here is the JavaScript code I am using: $scope.friends = ...

"Angular EventEmitter fails to return specified object, resulting in undefined

As I work on a school project, I've encountered a hurdle due to my lack of experience with Angular. My left-nav component includes multiple checkbox selections, and upon a user selecting one, an API call is made to retrieve all values for a specific " ...

Transferring and bringing in components in React without ES6

I'm currently working on a react project and I want to export my ShoppingList class. However, I prefer not to use ES6 as I find it confusing. Here is the code for the ShoppingList class: class ShoppingList extends React.Component { render() { ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

Steer clear of using the character sequence "&#8220;" in both PHP and

I am struggling with the encoding (I think). A script I wrote fetches a PHP file through AJAX that generates a JSON file. The JSON file appears as follows in Firebug: ["&#8220;This is a word&#8221; This not"] I am trying to find a way to remove & ...

Navigate to a new webpage using a string of characters as a legitimate web address

When a user performs a search, I pass the search term as a string to direct them to a new page. How can I create a valid URL (e.g., remove spaces from the string)? It's crucial that the next page can recognize where any spaces were in the search word ...

Vue.js: The v-for directive demonstrates distinct behavior with the utilization of template literals

What is the difference in behavior of v-for when using numbers versus template literals? Consider the following scenario: new Vue({ el: "#app", }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div i ...

After refreshing the page, the data stored in the localStorage array gets replaced

After refreshing the webpage, my localStorage array values are being overwritten. During a session, I am able to update values on the front end, and the array in localStorage gets updated accordingly. However, if multiple inputs are changed during a sessio ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

Visualizing data with a grouped bar chart in D3.js

I am currently working on creating a vertical bar chart using D3.js, similar to the one shown in this https://i.sstatic.net/pig0g.gif (source: statcan.gc.ca) However, I am facing an issue as I am unable to display two sets of data for comparison. Follow ...

Using ReactJS with Typescript: attempting to interpret a value as a type error is encountered (TS2749)

Currently, I am working on coding a ReactJS class using Typescript and Material-ui in a .tsx file. In one of the custom components that I have created, I need to establish a reference to another component used within this custom component. export class My ...

Click event for a tree component in Angular 2

How can I trigger a node click event in an Angular tree component? import { TREE_ACTIONS, KEYS, IActionMapping } from 'angular2-tree-component'; const actionMapping:IActionMapping = { mouse: { click: TREE_ACTIONS.TOGGLE_SELECTED_MULTI } ...

Vue-router and middleman combination displaying '404 Error' upon page refresh

I'm in the process of developing a website that utilizes Middleman (Ruby) on the backend and VueJS on the front end, with vue-router managing routing. Specifically, in my vue-router configuration, I am rendering the Video component on /chapter/:id as ...

Create a string that has been properly formatted

I need a javascript alternative to the StringEscapeUtils in java, specifically for converting input strings like: He didn't say, "Stop!" The desired output format should be: He didn't say, \"Stop!\" Is there a similar function a ...

Have you considered utilizing encodeURIComponent to encode both the key and parameter values?

When I use encodeURIComponent in this code snippet: export function getDownloadFileUrl(fid: string,bgColor: string) { const params = encodeURIComponent("id=" + Number(fid) + "&bgColor=" + bgColor); const config = { m ...

Ways to capture an error (message) following a request

When I send a request, if the status is not 200, I need to throw an error with an error message. apiService.createNewUser(data).then((response) => { if (response.ok) { return response.json() } else { throw new Error(???) } } ...

What causes AngularJS to generate an error when attempting to construct a URL for the src attribute of an iframe?

Recently, I've been working with AngularJS directives and encountered an issue while trying to use an expression in the src attribute of an iframe. The error message I received referenced a URL that didn't provide much insight: http://errors.ang ...