What is the best practice for defining a data type within a class structure?

Starting my journey with angular2. Your patience is greatly appreciated.

Here's what I've experimented with:

export class Navbar {
  name: string;
  submenu: {
    name: string;
  }
}

Tried using arrays and [] as well

export class Navbar {
  name: string;
  submenu: array;
}

This snippet lacks a declaration for submenu.

export class Navbar {
  name: string;
}

const NAVBAR: Navbar[] = [
  { name: 'Company Data' },
  { name: 'Client Data', 
    submenu: [
      { name: 'Balance' },
      { name: 'Settlement' }
    ]
  },
  { name: 'Bookie Data' },
  { name: 'Bank Data' },
  { name: 'Journal Entry' },
  { name: 'Journal Bank' },
  { name: 'Report', 
    submenu: [
      { name: 'General Ledger' },
      { name: 'Trial Balance' },
      { name: 'Profit/Loss' },
      { name: 'Balance Sheet' }
    ]
  },
  { name: 'Control' },
  { name: 'Input', 
    submenu: [
      { name: 'Company' },
      { name: 'Client' },
      { name: 'Bookie' },
      { name: 'Master' },
      { name: 'Client Agent' },
      { name: 'Bookie Balance' },
      { name: 'Import Client Data' },
      { name: 'Chart Of Account' },
      { name: 'Bank' },
      { name: 'Bank Company' }
    ]
  }
]

The error message from angular reads as follows:

app/app.component.ts(10,5): error TS2322: Type '({ name: string; } | { name: string; submenu: { name: string; }[]; })[]' is not assignable to type 'Navbar[]'.
  Type '{ name: string; } | { name: string; submenu: { name: string; }[]; }' is not assignable to type 'Navbar'.
    Type '{ name: string; submenu: { name: string; }[]; }' is not assignable to type 'Navbar'.
      Object literal may only specify known properties, and 'submenu' does not exist in type 'Navbar'.

Your assistance would be immensely valuable. Thank you!

Answer №1

When making adjustments, consider using an interface or type instead of a class, especially if you are not utilizing new.

Additionally, having submenu: array as mandatory may not be ideal since not every instance requires it. You can indicate this with a ?.

An interface setup could look like this:

export interface Navbar {
  name: string;
  submenus?: Navbar[];
}

This will allow for structures like:

const navbars: Navbar[] = [
  { name: 'Company Data' },
  { name: 'Client Data', 
    submenus: [
      { name: 'Balance' },
      { name: 'Settlement' }
    ]
  }
];

View Example

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

The function in JQuery that is being called using the onclick event is not functioning as anticipated on the PHP download

I have created a Php script that keeps track of the number of times a file is downloaded using Php and JQuery. The issue I am facing is that my function getStatus() calls the Php file every second, consuming a lot of bandwidth. I attempted to optimize by t ...

Bizarre text scenarios in JavaScript

I've come across something similar in certain libraries if ("testing" !== 'production') { "testing" !== 'production' ? warning(this instanceof Constructor, 'A React component is being called directly. Consider using ...

The Vuex state item is consistently found to be void of any content

After integrating Vuex into my project, I have encountered a peculiar issue. Within the filters module, the structure is as follows: import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default { namespaced: true ...

The process of invoking the parent class's Symbol.iterator function from the child class's Symbol.iterator can be achieved by following a specific

I have two TypeScript classes defined below. class BaseIter { constructor(public a: number, public b: number, public c: number, public d: number){} *[Symbol.iterator](): Iterator<number> { yield this.a yield this.b yield this.c y ...

What is the procedure for incorporating JavaScript into my tic-tac-toe game's HTML and CSS?

I have created a simple Tic Tac Toe game using HTML and CSS. Although there is no embedded Javascript, I do reference a Javascript file for functionality. Can anyone provide me with the most straightforward Javascript code that will display an 'X&apos ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

I encountered an issue with my autocomplete feature in Angular TypeScript where it was returning a [object Object] value

Issue with autocomplete displaying [object Object] value in Angular TypeScript I'm having trouble pinpointing the exact problem HTML snippet <mat-form-field style="margin-right: 10px;"> <input #productName matInput placeholder="Product" ...

Incorporating angularjs within a page loaded with jquery.load

Currently, I am in the process of developing a web application designed to cater to multi-device applications. The foundation of this project involves a framework built using nodejs, socket.io, and express which manages the distribution of views. This fra ...

What is the reason for receiving an error with one loop style while the other does not encounter any issues?

Introduction: Utilizing TypeScript and node-pg (Postgres for Node), I am populating an array of promises and then executing them all using Promise.all(). While pushing queries into an array during iteration over a set of numbers, an error occurs when the ...

What is the process of including metadata in stripe when completing a purchase?

const mergeData = function (prod, pot, data) { const newData = [...prod, ...pot]; const finalCheckout = []; for (let i = 0; i < newData.length; i++) { finalCheckout.push({ name: newData[i].plantName || newData[i].potName, images: [newData[i].images ...

Ensuring Redirection to Login Page Upon Refresh in React Router Dom

I have encountered a scenario where the customer needs to be directed to the login screen upon Browser refresh. For example: import "./styles.css"; import { Route, Routes, BrowserRouter as Router, Outlet, Link } from "react-router- ...

Dealing with React and Firebase Authentication Errors: How to Handle Errors for Existing Accounts with Different Credentials

According to the documentation at https://firebase.google.com/docs/auth/web/google-signin#expandable-1, when error.code === 'auth/account-exists-with-different-credential', signInWithPopup() should return an error.email. However, in my specific c ...

Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below: data(){ return { form : { attribute_1 : "1", //attribute 1 is true ...

- The click function is failing to work after an ajax call [Potential event delegation problem]

I have a webpage where I update the contents of an unordered list using $.get() every 5 seconds. The issue I am facing is that the click function for the list items is not working properly. Even though the list items are being updated correctly, there se ...

Modifying hidden field values with JavaScript does not carry over to the server side in Chrome

I created a custom user control that contains a hidden field which is set when a node is clicked on a Tree View Hierarchy control. The following function is responsible for handling the click event of the Tree View: function HandleTreeClick(evt) { va ...

Access to property 'nodeType' on AJAX request in Firefox has been denied due to permission error

On my webpage, I have integrated the Google Sign-in button along with gapi for interaction. After a successful authentication using the Google API, an AJAX call is made to the server using JQuery: var token = gapi.auth.getToken(); var data = { "to ...

Is it necessary to update the expiration time by refreshing the cookie with every request/response in Node.js?

Enhanced Authentication Within my Node.js backend powered by Express.js, I implement user authentication using JWT stored in an HttpOnly cookie that expires after a designated number of hours (N). A middleware verifies the validity of the JWT and either p ...

npm's protocol for handling callback errors

While exploring the coding style guidelines by npm, I stumbled upon a rather enigmatic suggestion: Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback. Thi ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

Real-time Dropdown Updating in PHP

I apologize if this question has been addressed previously, but I have attempted a search and have not found answers in other posts. The responses I did come across did not pertain to my specific question (which mostly revolved around dropdowns fetching re ...