Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types.

An example of a dish object could be:

{
      "id": "dish01",
      "title": "SALMON CRUNCH",
      "price": 120,
      "ingredients": [
        "MARINERAD LAX",
        "PICKLADE GRÖNSAKER",
        "KRISPIG VITLÖK",
        "JORDÄRTSKOCKSCHIPS",
        "CHILIMAJONNÄS"
      ],
      "options": [
        {
          "option": "BAS",
          "choices": ["RIS", "GRÖNKÅL", "MIX"],
          "defaultOption": "MIX"
        }
      ]
}

The current attempt is as follows:

enum DishOptionBaseChoices {
  Rice = 'RIS',
  Kale = 'GRÖNKÅL',
  Mix = 'MIX',
}

type DishOption<T> = {
  option: string
  choices: T[]
  defaultOption: T
}

type DishOptions = {
  options: DishOption<DishOptionBaseChoices>[]
}

type Dish = {
  id: string
  title: string
  price: number
  ingredients: string[]
  options: DishOptions
}

(uncertain if some should be interface instead of type)

The objective is to create enums for all "types" of options. The auto-suggestion functions well with the id, but encounters issues with the options.

https://i.stack.imgur.com/E3r91.png

Effective solution

type ChoiceForBase = 'RIS' | 'GRÖNKÅL' | 'MIX'

type DishOption<OptionType, ChoiceType> = {
  option: OptionType
  choices: ChoiceType[]
  defaultOption: ChoiceType
}

type Dish = {
  id: string
  title: string
  price: number
  ingredients: string[]
  options: DishOption<'BAS', ChoiceForBase>[]
}

Answer №1

Within the Dish type, you specified options: DishOptions, but then within the DishOptions type, you defined a property called options again. As a result, your options property is structured like this:

const dish: Dish = {
    options: {
        options: [{
            choices: ...
        }]
    }
}

If you intend for options to be an array of DishOption, update your Dish definition as follows:

type Dish = {
    id: string
    title: string
    price: number
    ingredients: string[]
    options: DishOption<DishOptionBaseChoices>[]
}

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

Eliminate an item from an array of objects utilizing a specific key

Here is the JSON data provided: var data= { 'A' : { 'Total' : 123, 'Cricket' : 76, 'Football' : 12, 'Hockey' : 1, 'None' : 10 }, 'B&ap ...

Utilizing JSON-Stat in NodeJS

I've recently started using the JSONStat toolkit, but I keep encountering this error message: let method = init.method || input.method || 'GET'; ^ TypeError: Cannot read property 'method' of null ...

Reinitializing a form with jQuery validation inside a modal box

While utilizing jQuery Validate in a form within a jQuery dialog, I am encountering an issue. Upon closing the dialog, I aim to clear all form fields and reset any fields with error feedback displayed. Although the fields are being reset to blank as expec ...

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

Using cakePHP to submit a form using ajax

While submitting a form using ajax and attempting to return a json response, I encountered an issue of receiving a missing view error. Adding autoResponder=false resulted in no response at all. This is happening while working with cakephp 2.5 In the same ...

retrieve the most recent file following a $group operation

I am currently utilizing the official MongoDB driver specifically designed for Node.js. This is how my message data is organized. Each post consists of a timestamp, a user ID, and a topic ID. [ { "_id" : ObjectId("5b0abb48b20c1b4b92365145"), "t ...

What is the best way to retrieve a Promise from a store.dispatch within Redux-saga in order to wait for it to resolve before rendering in SSR?

I have been experimenting with React SSR using Redux and Redux-saga. While I have managed to get the Client Rendering to work, the server store does not seem to receive the data or wait for the data before rendering the HTML. server.js ...

What is the best way to choose a random ID from a table within specified time intervals in MySQL?

I need to retrieve a random ID from the table nodes within the last 15 seconds. I attempted the following code, but it produced a lengthy output: const mysql = require('mysql'); const connection = mysql.createConnection({ host ...

Tips for assessing a JSON-decoded boolean value to see if it is equal to "true"

Regarding the topic of Checking a JSON decoded boolean value in Perl, I have a validation subroutine where I need to perform the following check, my $boolean = 'true'; my $json_string = '{"boolean_field":true}'; my $decoded_json = fr ...

Receiving an error when trying to access the 'get' property of $http within a nested function

Encountering the following error angular.js:13550 TypeError: Cannot read property 'get' of undefined at Object.DataService.getDataFromAPI I seem to be struggling with the $HTTP.get function. Any insights on what might be going wrong or ...

Pass data between different parts of the system

Utilizing the angular material paginator has been a great experience for me. You can check it out here: https://material.angular.io/components/paginator/examples. The paginator triggers an event which allows me to print the page size and page index. This f ...

Exploring the use of jQuery's .filter() method to showcase JSON data

I am currently working on a webpage that includes images, details, and a search input option using JSON objects. The issue I'm facing is that the search function does not yield any results, even though the data from the JSON object displays correctly ...

Converting Javascript game information into PHP

Once the player loses, I need their score to be updated in the database using PHP. There is a separate JavaScript class that runs the game, utilizing setInterval to check the index.php function and update the database if the player loses. However, the issu ...

Steps to arrange data in a SQL query based on the value found within a database field in JSON format

Array ( [0] => Array ( [20] => stdClass Object ( [qopid] => 20 [data] => {"room":0,"category":0} ) [21] => stdClass Object ...

Progressive rendering of a substantial mesh using three.js

How can I efficiently render a large static mesh in three.js, even if it's 2 GB with tens of millions of polygons? My plan is to stream the mesh geometry buffers into indexedDB and render them progressively to the screen, all while maintaining an int ...

Ajax - Receiving a Null Value When No Fresh Data is Present

I am currently working on a notification system and I just need to address one final detail to ensure it functions perfectly. During the initial ajax load, the script utilizes the php variable to interact with the server-side script in search of new conte ...

Ways to have MongoDB present nested JSON data as an array?

I recently came across some interesting data: { "_id" : ObjectId("5461e16ee7caf96f8f3584a2"), "num_marcacao" : "100", "sexo" : "Fêmea", "idade" : "20", "bigdata" : { "abortos" : [ { "data_aborto" : ...

Tips for showcasing images retrieved from a REST API on the frontend, with the condition that only one image should be displayed using multer

I am experiencing an issue where only the image logo is being displayed in my frontend, rather than the entire image that I uploaded in string format on my backend. Can someone please help me troubleshoot this error and identify what may be wrong with my c ...

Utilize jQuery's .append() function to dynamically insert content into your webpage

I currently have tab elements set up like this: <div class="tab-pane fade active in" id="tab-a"> </div> To populate the content of that tab with a JavaScript string array, I am using the following code snippet: var full_list = ""; for (var ...

The file raphael.2.1.0.min.js contains a UTF-8 byte sequence that is not valid

Currently, I am attempting to implement the justgage plugin on my Rails 4 application. However, an error has arisen: raphael.2.1.0.min.js contains an invalid UTF-8 byte sequence The only changes I made to my application.js were: //= require justgage.1 ...