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

Setting the JSON encoder in marshmallow is a straightforward process

Is there a way to customize the JSON encoder used in the marshmallow library in order to serialize a Decimal field? I believe I can achieve this by overriding the json_module either in the base Schema or Meta class, however, I am unsure of how to go about ...

When a JavaScript/jQuery open window popup triggers the onunload event after the about:blank page has been

Imagine you have a button that triggers a popup using window.open(): <button id = "my-button">Open window</button>​ You also want to detect when this popup window closes. To achieve this, you can use the following code: $('#my-button& ...

Guide: Implementing Vuex store within a plugin

I recently developed a custom Vue plugin which includes a customized instance method import Echo from 'laravel-echo'; import Vue from 'vue'; import config from '@/config'; const echor = { install(Vue){ Vue.prototy ...

Issue with Jquery focus on dropdown not working

I am facing an issue with setting up the dropdown feature for my list. It's similar to ul li:hover ul li. What I'm trying to achieve is something like ul li:focus ul li in jQuery because I don't think it can be done using CSS. The desired ou ...

JavaScript problem with hovering action causing additional buttons to appear

Currently, I am developing a user interface where, upon hovering over an LI element, 2 buttons appear to provide additional functionality - "edit" and "remove". However, I am facing challenges with the mouse hit zones. The mouseover function works effect ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

Managing various iterations of identical repositories

Currently in the process of constructing a library of unique react components that are being utilized in various downstream applications. To incorporate these components into my downstream applications, I rely on the package.json. Recently, I began ponde ...

Dealing with Cyrillic character escaping issue in Rails JSON with ExtJS framework

I'm encountering an issue regarding the handling of Cyrillic characters in the JSON output from Rails: {"success":true,"total":"2","offices":[{"address":"addr","created_at":"2011-06-03T11:55:09Z","description":"desc","id":1,"name":"Office 1","publish ...

Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value. Below is the code snippet: export default defineCo ...

When attempting to make a post using Prisma's ORM, users may encounter an error message indicating that the post function

Creating a basic prisma application using express and node to query a local mysql database. Encountering an error when calling await prisa.list.create(), details provided below. Here is the script.js code snippet from the HTML page: addItemForm.addEvent ...

Exploring the process of performing an AJAX JQuery HTTP request using JavaScript and PHP on the server side - any tips?

Greetings! I have developed a web application using HTML, CSS, and JavaScript. To enhance functionality, I have integrated Bootstrap and jQuery into the project. The application comprises both client-side and server-side components. Let's take a look ...

Utilize the ng2-select component to incorporate multiple instances within a single webpage

Can someone help me figure out how to use two ng2-select components in my modal? I've checked out the documentation, but it doesn't provide any information on using more than one select. I'm not sure how to capture the selected values of ea ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

Tips for resolving the problem with a malfunctioning ChartJS legend

I have been working on my project using chartjs and all the charts are displaying correctly except for the legends. No matter what I try, the legend is not showing up. Here's the code snippet: var ctx1 = document.getElementById("chart1").getContext(" ...

Exploring Javascript/JQuery parameters based on data types

I'm a bit confused about whether the title accurately reflects my question. I need help understanding how jQuery deals with functions that are called with different argument combinations, such as ("Some String", true, function(){}) and ("Some String", ...

Toggle the status of active to inactive instantaneously with the click of a

Incorporating DataTables with ajax using PHP CodeIgniter Framework has presented me with a challenge. I am struggling to toggle between Active and Inactive buttons seamlessly. My desired outcome: When the Active button is clicked, it should transition ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

I am having difficulty with my JavaScript code not being able to interpret the JSON output from my PHP code. Can anyone help me troubleshoot

Having trouble working with an AJAX call and handling the JSON object it generates in JavaScript? Here's a sample snippet of PHP code returning the JSON object: echo json_encode(array("results" => array(array("user" => $member['user'] ...

Issues involving the handleChange function in React can be a frustrating and common hurdle

I am encountering an issue with the handleChange function in my React project. Upon loading data from JSONPlaceholder and clicking on the 'Edit' button, a form is displayed with the selected user's information. However, when trying to edit ...

Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error: UnhandledPromiseRejectionWarning: TypeError: Cannot r ...