Enum-Based Object Indexing

The structure I am currently working with is as follows;

import data from "../data.min.json";

export enum TileType {
  tree = 'tree',
  rock = 'rock'
}

interface MapTile {
  walkable: boolean;
  positions: number[][];
}

export type MapTiles =  {
  [key in TileType]: MapTile
}

export interface Level1 {
  mapTiles: MapTiles;
}

export interface RootObject {
  level_1: Level1;
}

export default data as RootObject;

Everything seems to be functioning correctly. However, I encountered an issue when trying to implement it in the following way;

const entries = Object.entries(data.level_1.mapTiles);
entries.forEach(([tileType, data]) => {
  
})

Instead of receiving the Enum value, 'tileType' holds a string. How can I access the Enum value instead?

Here is an overview of the data structure being used:

{
  "level_1": {
    "mapTiles": {
      "tree": {
        "walkable": false,
        "positions": [
          [ 0, 0 ], [ 0, 40 ], [ 0, 80 ]
        ]
      },
      "rock": {
        "walkable": false,
        "positions": [
          [2, 4], [5, 7]
        ]
      },
    }
  }
}

Answer №1

When it comes to the typings for Object.entries in lib.esXXX.object.d.ts, there is an important consideration to keep in mind. In lib.es2017.object.d.ts for example, the typings are defined as follows:

entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][];

As shown, the key is assumed to be a string. However, if you make a simple adjustment as follows:

entries<T, U extends keyof T>(o: T): [U, T[U]][];

You can create your own typed function without modifying the standard library:

const objectEntries = <T, U extends keyof T>(inputObject: T) => {
  return Object.entries(inputObject) as [U, T[U]][]
}

By using this approach, you can achieve the desired typings. To illustrate, consider the following code snippet:

objectEntries(data.level_1.mapTiles).forEach(([
  tileType, // correctly inferred as "tree" | "rock"
  data
]) => {})

https://i.sstatic.net/4fzdJ.png

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

Step-by-step guide on retrieving JSONP data from Angular service within view by utilizing expressions

I have been developing an Angular application that retrieves data from the Strava API. While experimenting with $http.get, I realized that separating the logic into a dedicated service would be more organized, allowing my controller to simply call the serv ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

Ways to extract values from a javascript hash map by exclusively incorporating an array

So here's the issue I'm encountering. Let's consider the following scenario: let surfaces: Map<any, any> = new Map([{"83.1" => Object}, {"84.1" => Object}]) let arr1 = ["83.1"] This is the desired o ...

obtain a jQuery element from a function

Can a function return a $ object, or does it need to be converted to a string before being returned? function returnObj() { obj = $("<img id='' src='' />"); return obj; } var obj = returnObj(); alert(obj); //returns [obj ...

I am requesting for the average to be adjusted based on the user's choice between Hindi or English percentage scale

Currently, the average is being calculated in the HTML code. When a user input is changed, the average breaks. What can be done to update the average for each individual person? Controller var app = angular.module('myApp', []); app.controller( ...

Utilizing Knockout to Render JSON List Items

Utilizing Knockout.js to dynamically update a view from JSON response has been my current focus. The structure of the JSON is as follows: var data = { "Properties": { "Engine Capacity": "1499cc", "Doors": 3, "Extras": [ "LED lights", ...

Transforming a JToken into a sophisticated object through the use of the ToObject method

Apologies for any language barriers, but I could really use some assistance with the ToObject method. Here is a snippet of the classes I'm working with: namespace Projects { public class AProductType { public DateT ...

Creating a String-only pattern Validator: A step-by-step guide

Below is the code I've written: ***<input type="text" placeholder="First Name" name="firstName1" [(ngModel)]="firstName" #firstName1="ngModel" required pattern="^[a-z0-9_-]{8,15}$" >*** ...

Unable to accept the link ID in the modal

Presently, I am facing an issue with a modal that links a product with a customer and involves product discount calculations. The customer is automatically selected using the modal id, and the product is chosen through select options with a while loop. T ...

Exploring the world of JSON and JSONP with JQuery

I'm experiencing some issues with my $.getJSON method, whereas the $.ajax method works perfectly fine. Let's first take a look at my getJSON call: $.getJSON("http://localhost:1505/getServiceImageList?callback=loadImagesInSelect", loadImagesInSel ...

What is preventing me from successfully transmitting the JSON string to the server using C#?

After successfully sending a JSON string to the server, I decided to make a modification. Initially, my JSON looked like this: string json = "{\"registration_ids\":[\"" + regId + "\"]}"; But when I added more data to it like this ...

Using type as an argument in a hook in a similar fashion to how it is

My custom hook utilizes Zustand and is capable of storing various data types. However, I am looking to specify the type of data that will be stored similar to how it is done with the useState hook. import { Profile } from "@/types"; import { crea ...

Using the TIMESTAMP data type in PostgreSQL and getting the most out of it

After saving a Luxon datetime value in a TIMESTAMP(3) type column in a postgres database, I encountered difficulty using it for various operations like converting time zones. Despite creating the object with the code snippet below: const { DateTime } = req ...

Exploring unique forms with the turfjs polygon difference() function

While implementing the difference() function for my polygon map, I encountered a problem where unexpected shapes would appear or disappear when zooming in on the map. These shapes should not be there. The polygons involved are of type MultyPolygon and Poly ...

Assign a Value to a Hidden Input Type When a User Submits a Form

I have a straightforward form set up in the following code. I am looking to add the value entered in the rm_accounts text box to the hidden page_confirm input value at the end of the URL. I hope that explanation is clear. In simple terms, if the user type ...

How to Import Components that Have Imports in MDX-Bundler within Nextjs

Is it possible to use mdx-bundler to import a file that itself imports another file? Currently, in my .mdx file, I have the following code: import MyComponent from './MyComponent' This is my *mdx* file. <MyComponent /> This works fine a ...

Customizing the appearance of the Bootstrap Typeahead

I've been experimenting with the Bootstrap Typeahead for my search feature. I successfully implemented the dropdown list using Ajax. However, I am looking to customize the width, padding, and background color of the dropdown menu, which is currently w ...

Limit the ng-repeat directive based on the length of the array, using an ng-if condition

<div ng-repeat="badgesData in deptUSersData.badges | limitTo : 7 track by $index"> ........content....... </div> If the length of deptUSersData.badges is more than 8, I want to apply a limit of 7. How can I achieve this? My desired ...

Difficulty with parsing JSON in JavaScript and retrieving values by key

I'm encountering an error response within the ajax error function; $.ajax(Request).error(function (Response) { var content = JSON.stringify(Response.responseText); var obj = JSON.parse(content); console.log("Response.r ...

webpack is encountering difficulty resolving the node_modules material-icons directory

Encountering an Error ERROR in ./node_modules/material-icons/iconfont/material-icons.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_mod ...