Issue in Typescript when accessing an enum within an object key

I have encountered an issue while trying to reference an enum in typescript as the value of an object property.

Here is the code snippet:

types.ts

export enum BlockContentResolverTypes {
  RAW_STRING_RESOLVER = 'raw::string::resolver',
  RAW_NUMBER_RESOLVER = 'raw::number::resolver',
}

export interface BlockAnswerType {
  id: string;
  key: string;
  value: boolean | string | number;
  label: {
    type: BlockContentResolverTypes
    value: string;
  };
}

The goal is to make the label.type accept values from the BlockContentResolverTypes enum such as raw::string::resolver or raw::number::resolver.

However, when importing a JSON object and assigning it the type of BlockAnswerType, a type error occurs.

Below is the imported object:

data.json

{
  "data": {
    "id": "b608dbcd-f6c0-423d-9efd-c957af86a3b6",
    "key": "yes",
    "label": {
      "type": "raw::string::resolver",
      "value": "Yes!"
    },
    "value": true
  }
}

The Typescript error message received is:

Type 'string' is not assignable to type 'BlockContentResolverTypes'.

Initially, I tried declaring all the enum values manually, but that did not resolve the error. Where am I going wrong and what would be the correct approach for this situation?

Answer №1

It's important to consider how you are handling the JSON data and where it is being processed. When parsing the JSON string, make sure to assert the type so that the compiler can recognize it.

Remember, you must verify that the JSON structure aligns with the defined type (and this validation can also be done at runtime by checking all properties after parsing).

Explore TypeScript Playground for testing your code: TS Playground

const json = `{
  "data": {
    "id": "b608dbcd-f6c0-423d-9efd-c957af86a3b6",
    "key": "yes",
    "label": {
      "type": "raw::string::resolver",
      "value": "Yes!"
    },
    "value": true
  }
}`;

const blockAnswer = JSON.parse(json).data as BlockAnswerType;
blockAnswer.label.type // BlockContentResolverTypes

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

Unlocking Iframe Mode in CKEditor 4

I've encountered a difference between CKEditor 3 and CKEditor 4. In CKEditor 3, when I call the method CKEDITOR.replace('#textAreaId'), it wraps the editor in an iframe. However, in CKEditor 4, when I call the same method (not inline), the i ...

Easiest homemade variations and pairings

Imagine having a basic array like ["apple", "banana", "lemon", "mango"];. For example, if we were to find the straightforward hand-rolled combinations of this array, selecting 3 items, but allowing for repetition: let array = ["apple", "banana", "lemon", ...

Watching the $scope variable using $watch will result in triggering even when ng-if directive is used, displaying

Encountering an unusual behavior in AngularJS that may appear to be a bug, but there could be a logical explanation. A certain value is being passed to a directive as an attribute. Within this directive, the parameter is being watched using $scope.$watch. ...

Encountering issues with scope: Unable to retrieve value and receiving an error message stating 'Cannot assign value to undefined property'

var mainApp = angular.module("Main", []); mainApp.controller("CtrlMain", [ function ($scope) { $scope.amount = 545 }]);` var app = angular.module("Main", []); app.controller("MainCtrl", [ function ($scope) { $scope.value = 545 ...

The AngularJS application appears to have trouble accessing a local text file, even when it is deployed on

Within the same directory of my application deployed on IIS, there are 4 files: home.html Angular.js data.txt web.config (Automatically generated by IIS for default document) I am looking to display the content of 'data.txt' on 'home.html ...

What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array? I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function: Array.prototype.removeIf = function(condition: Function): any[] { var copy: any[] ...

Error: jQuery Validation not triggering in Bootstrap modal window

My attempts to use jQuery Validation for form validation inside a modal have hit a dead end. The validation doesn't trigger at all, not even an error message is displayed. Upon debugging, a warning emerged: No elements selected for validation; retu ...

Is it possible to run a web game on the same URL?

While working on quickly prototyping my ideas, I have been utilizing Express with Mongo and have successfully implemented a mongostore cookie storage system. Here's what I'm wondering: Can I keep everything happening on one page, specifically &a ...

Direct your attention to the cursor problem in Internet Explorer

Here is a snippet of code that automatically changes background images: function changeBackground() { currentBackground++; if(currentBackground > 3) currentBackground = 0; $('body').fadeOut(0, function() { $('body&ap ...

Steps for generating tab panels and their respective content using a v-for loop

I am currently utilizing Vue 3 in combination with Bootstrap 5. My objective is to incorporate multiple Tabpanels within a v-for. Each of these Tabs should feature distinct content. To achieve this, I attempted placing my Tabs and their respective Conten ...

Struggling to organize data into a hierarchy using the D3.js nest function

Attempting to build a d3.js tree, I need my data to be in hierarchical form before using d3.treeLayout. Currently, here is what my json array looks like: var data = [ {"group":"1","price":"36599.88", "cy":"44260"}, {"group":"2","price":"36599 ...

Required inputs do not disrupt the form's action flow

Here is the HTML code that I am working with: function document_save_changes(){ if (is_key_dirty == true){ var elm = document.getElementById('set_doc_button'); key_change_warning(elm, 'D'); return; } if (document_save_warning('A ...

The ngBindHtml feature in AngularJS 1.2 does not handle processing of line breaks (/r & /n)

I have a string with a lot of extra whitespace, as it appears on my server: var care_description = "MATERIAL\r\n \r\n 56% Acrylic, 24% Rayon, 20% Polyester\r\n \r\n CARE\r\n \r\n Machine ...

I am experiencing issues with my drag and drop feature not functioning properly

I am looking to reposition my #timebase1 div within the draghere div. Currently, it only moves the start of the div, but I would like to be able to drop it anywhere inside the draghere div. function handleDrag(e) { var id = e.id; ...

Loading remote common data once in AngularJS and sharing it across multiple controllers: a guide

I have a challenge in my AngularJS application - I need to load a large dataset from an HTTP request just once and share it across multiple controllers. To achieve this, I created a factory that handles the data retrieval: angular.module('app'). ...

Ways to categorize items using JQuery based on their hierarchical structure

I am looking to organize the following HTML content: <h2>State the Issue  </h2> <h3>Provide information about your objective</h3> <h3>Share any error messages received</h3> <h2>Outline Your Attempts  ...

Revamp your website with an AJAX-powered login form that dynamically updates the page content upon successful

Imagine having a page with a dynamic login/logout feature in the header that operates smoothly via AJAX. When a user is not logged in, display a message saying "Hey, login" and provide the option to login via AJAX, which functions correctly. However, onc ...

Is there a way to apply filters to jquery datatables during initialization process?

Is there a way to server-side filter datatable during initialization? I attempted the following code: function tableFilter(arg1, param2, value3) { var searchTable = $("#tblsearch").dataTable({ "bRetrieve": true, "b ...

Loading preferred routes in Angular 6+ Universal for faster performance

In my Angular 7 application, I have Angular Universal set up with Express and I am also utilizing Angular Routing. My goal is to have only the pre-login routes (marketing views) rendered server-side, while post-login routes are loaded using traditional cli ...

Removing all table rows except one in Jquery

I currently have this code in my view: <script> $(document).ready(function() { $("#add_instruction").click(function(){ $("#instructions").append("<tr><td></td><td><input type='text' name='rec ...