How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly.

export interface Header {
   parentTitles: string;
   childHeaders: ChildHeader[];
   titleIcon: string;
   url: string;
  }

export interface ChildHeader {
   childTitles: string;
   siblingHeaders: SiblingHeader[];
   icon: string;
   url: string;
 }


export interface SiblingHeader {
  siblingTitles: string[];
  icon: string;
  url: string;

}

In my comp.ts file, I have the following code:

 headers: Header = [
   {
  parentTitles: 'Settings',
  childHeaders: ChildHeader = [{
    childTitles: 'General Setup',
    siblingHeaders: SiblingHeader = [{
      siblingTitles: ['Vessel', 'Port', 'Owner', 'Engine Type', 
    'Vessel Type'],
      icon: '',
      url: ''
    }],
    icon: '',
    url: 'home/general-setup'
      }]
   }

  ];

The issue is that the ChildHeader and SiblingHeader are showing up as undefined. Can someone help me figure out how to fix this?

Thank you!

Answer №1

When you instantiate an object, remember to use the syntax propertyName: value. Avoid using types as values because they can lead to errors. For instance, if you reference SiblingHeader as a value, it's incorrect because it's a type and not a value.

However, by declaring header: Header, you are already setting up the header object as a header with an array of ChildHeader. Each of these arrays contains objects that have the property siblingHeaders, which in turn is an array of SiblingHeader. In essence, the types for the properties in object literals are derived from the object itself, so specifying them explicitly is unnecessary.

const headers: Header[] = [{
  parentTitles: 'Settings',
  childHeaders: [{
    childTitles: 'General Setup',
    siblingHeaders: [{
      siblingTitles: ['Vessel', 'Port', 'Owner', 'Engine Type',  'Vessel Type'],
      icon: '',
      url: ''
    }],
    icon: '',
    url: 'home/general-setup'
  }]
}];

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

Having trouble with UpdateMany in mongoose, but it works perfectly in mongodb when executed directly

I am attempting to update and insert data in mongoose. After sending some requests, I receive the following result: let obj = [ {name: aaa, age: 10}, {name: bbb, age: 11}, {name: ccc, age: 12}, ] My goal is to update all existing documents an ...

"Error encountered: Array is undefined when using the map and subscribe functions in Ionic

I have developed a service that is supposed to retrieve data from a JSON file and assign it to an array called 'countries', which will be used throughout the application on multiple pages. However, when I call the method getCountries, the countri ...

Step-by-step guide to linking a matTooltip with a disabled mat-tab

Is there a way to attach a matTooltip to a mat-icon in a disabled mat-tab? It seems that this feature is disabled when the mat-tab itself is disabled. Has anyone else encountered this issue? (I am unable to place the mat-tab within a div, of course) Than ...

typescript library experiencing issues with invalid regex flags in javascript nodes

I am facing an issue while attempting to import a plain JavaScript module into a Node application written in TypeScript. The error below is being thrown by one of the codes in the JavaScript module. b = s.matchAll(/<FILE_INCLUDE [^>]+>/gid); Synta ...

Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to thei ...

How come the value assigned to the [(ngModel)] variable does not show up as the selected value in the PrimeNG drop-down menu?

When passing data from the parent to child component, the normal text input is populated with the data received from the parent, but the same does not work with dropdowns. The code block where data is passed to the variable enteredName functions as intend ...

Encountering errors with ng build --prod in Angular 2, but no issues when running ng serve

After attempting to deploy my Angular 2 app to Heroku, I encountered a daunting list of errors when trying to build for production. Interestingly, the app runs smoothly without any issues or errors when using 'ng serve'. You can view the full li ...

Is it possible to utilize TypeScript version 2.0.6 in conjunction with Visual Studio 2017?

Is it possible to utilize TypeScript 2.0.6 with Visual Studio 2017, or do I need to use a version greater than 2.1? Also, can you explain the difference between Microsoft.TypeScript.Compiler and Microsoft.TypeScript.MSBuild? If I don't have Microsof ...

The element is inferred to have the 'any' type. No index signature matching the parameter type 'string' was found on the 'User1' type

I have been experimenting with computed properties in TypeScript, but I've encountered a specific issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User1'. ...

Setting the base href in Angular using an environment variable for a Tomcat or other application server - a step-by-step guide

Is it possible to set the base href using an environment variable in a Tomcat or application server? For instance: index.html <base href="/${environment.tomcat}/"> Or is there a way to utilize an environment variable for the operating system? ...

Toggle the enableCheckboxSelector based on a specific condition

In my implementation of angular slickgrid, the enableCheckboxSelector is set to true by default in the grid options. However, I need to selectively hide checkboxes for all rows based on a dropdown value change. I tried the following code snippet: if(isRead ...

Fake AxiosInstance. In need of obtaining response in a single test

In my api.ts file import axios from 'axios' export const api = axios.create({ baseURL: 'http://localhost:3333/', }) Within my react-page.spec.tsx file: import React from 'react' import '@testing-library/jest-dom&apo ...

Angular list not refreshing

As a newcomer to Angular, I am facing a basic issue where my list does not get updated when I add a new object to my array. Whenever I tap on a button to add a new object to the array-list, the list fails to update. Additionally, I am grouping my array-li ...

Angular HTTP Interceptor encountering issue with TypeError: (0 , x.fromPromise) function is not recognized

I have implemented the following code snippet to attach reCAPTCHA v3 to an HTTP Request: @Injectable() export class RecaptchaInterceptor implements HttpInterceptor { constructor(private recaptchaService: ReCaptchaService) { } intercept(httpRequest: HttpRe ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

What is the best way to implement React ErrorBoundary in conjunction with redux-observable?

When dealing with asynchronous code, React Error Boundaries may not function as expected. In my case, I am using redux-observable and rxjs to retrieve data from an API. To handle errors, I am trying to utilize the catchError function provided by rxjs. I ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Python Flask-Socketio server deployed on Google Cloud App Engine Flexible environment

I need assistance deploying a Flask SocketIO server on App Engine. Below are the necessary imports and how the server runs: from typing import List from flask_socketio import SocketIO, join_room, leave_room, send, emit from flask import Flask, render_ ...

What is the most effective way to structure a React function incorporating nested objects and mapping?

As a newcomer to Typescript, I am facing challenges in properly typing the following code snippet. I have experimented with Interfaces and individually typing properties as well, but it seems like I am only scratching the surface and encountering new typin ...

Using lambdas in JSX attributes is not allowed because it can negatively impact rendering performance

I encountered an error when using the following code:- <FieldArray name="amenities" render={arrayHelpers => ( <div> {values.amenitieslist && values.amenitieslist.length > 0 ? ( val ...