It is impossible to declare a class attribute that has the same type as the class itself, creating a self-referencing hierarchy

My Angular model class has properties that reference the class itself:

export class ItemCategory {
  constructor(
    public parentCategory?: ItemCategory, 
    public subCategories?: ItemCategory[], 
    public name?: string, 
    public description?: string
  ) { }
}

When I try to compile my Angular code, I encounter the following error:

ERROR in src/app/models/entities/itemCategory.model.ts(9,14): error TS2395: Individual declarations in merged declaration 'ItemCategory' must be all exported or all local.
src/app/models/entities/itemCategory.model.ts(28,10): error TS2395: Individual declarations in merged declaration 'ItemCategory' must be all exported or all local.
src/app/models/entities/itemCategory.model.ts(28,10): error TS2440: Import declaration conflicts with local declaration of 'ItemCategory'.

Is there a way to properly reference the class within itself?

Edit: files utilizing this class

src\app\models\services\itemCategory.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ItemCategory } from "../entities/itemCategory.model";

@Injectable({providedIn: 'root'})
export class ItemCategoryService {
  constructor(private http: HttpClient) { } 

  public getAll() : Observable<ItemCategory[]> {
    return this.http.request<ItemCategory[]>("get", `api/ItemCategory`, { body: null });
  }

  public get(id: number) : Observable<ItemCategory> {
    return this.http.request<ItemCategory>("get", `api/ItemCategory/${id}`, { body: null });
  }

  public add(itemCategory: ItemCategory) : Observable<number> {
    return this.http.request<number>("post", `api/ItemCategory`, { body: itemCategory });
  }

  public update(id: number, itemCategory: ItemCategory) : Observable<number> {
    return this.http.request<number>("put", `api/ItemCategory/${id}`, { body: itemCategory});
  }

  public delete(id: number) : Observable<void> {
    return this.http.request<void>("delete", `api/ItemCategory/${id}`, { body: null });
  }
}

src\app\models\repository.ts

import { Injectable } from '@angular/core';

import { ItemCategory } from "./entities/itemCategory.model";

import { ItemCategoryService } from "./services/itemCategory.service";

@Injectable()
export class Repository {
  constructor(
    private itemCategoryService: ItemCategoryService
  ) {
      this.itemCategoryService.getAll().subscribe(response => this.itemCategories = response);
  }

  itemCategories: ItemCategory[];
}

Answer №1

It seems like you may be redeclaring the class and importing it unnecessarily. I believe I have replicated the issue based on my understanding.

Check out this link for reference.

Here is an example of what might be causing the issue:

// This may be causing the issue, unnecessary import here
import { ItemCategory } from './ItemCategory';

export class ItemCategory {
  constructor(
    public parentCategory?: ItemCategory, 
    public subCategories?: ItemCategory[], 
    public name?: string, 
    public description?: string
  ) { }
}

In the scenario below, there is no need to redeclare the class. Simply import it and use it where needed, like in the example below:

import { ItemCategory } from './ItemCategory';
export class HelloComponent {
  @Input() name: string;

  sample: ItemCategory;
}

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

Encountered a setback while constructing a library of Angular 7 components

While I successfully created a component library in Angular version 11 without any issues, I encountered an error when trying to build a component library in Angular version 7. Cannot find module 'tsickle/src/tsickle' Require stack: - D:\Ang ...

Change the @select variable to an object, a basic variable, or delete the AnonymousSubject

I'm utilizing Redux architecture within Angular. In my component, I am accessing the state's value using the @select (select pattern). However, when I try to log the @select variable to the console, I see the output as AnonymousSubject. ...

Issue with TypeScript while trying to define a property of a named function expression using 'let' instead of 'const'

As I continued my journey through the TypeScript handbook, I stumbled upon an intriguing concept while learning about Call Signatures. The code snippet provided in the handbook goes like this: type DescribableFunction = { description: string; (someArg: n ...

Solution for dealing with error 'Cannot find Property length on type {} in React using TypeScript

Any ideas on how to fix the error "Property 'length' does not exist on type '{}'"? Below is the code snippet causing the issue: //component const SearchResults = ({ results }: { results: {} }) => { let pageCount = results? ...

Exploring FileReader in conjunction with React and Typescript

I am facing an issue while trying to upload a JSON file using an input element of type file. When I attempt to use the onload method on FileReader in TypeScript, I receive an error message saying "Cannot invoke an object which is possibly 'null'. ...

Issue: NG05105 - Unforeseen artificial listener detected @transform.start

Encountered an issue in my Angular 17 app using Angular Material during the execution of ng test: Chrome browser throws 'app-test' title error in the AppComponent with the following message: Error: NG05105: Unexpected synthetic listener @ ...

Adding onBlur validation for radio buttons and checkboxes in Angular Material UI

Currently, I am working on implementing checkboxes and radio buttons using Angular Material UI. My main issue lies in achieving the desired red outline effect when a required field is left unselected by the user. Even after applying the necessary 'req ...

Issue with handling multiple input files in an *ngFor loop

I am facing difficulties in targeting the correct input within a *ngFor loop. When I include an image with the first input (Certificat dimmatriculation), it displays a placeholder image and a delete button to reset the input, but it appears under both divs ...

What steps should I follow to set up a dynamic theme in an Angular Material application?

I have spent countless hours trying to find clear documentation on setting up an Angular Material app with a theme, including changing the theme dynamically. Despite searching through numerous search results and visiting various pages, I have not been able ...

Exploring Angular: Understanding Events and Addressing the Error Message "subscribe is not a function"

Recently, I delved into the basics of Angular 4 and encountered a roadblock while trying to listen to an emitted event. Let me share a simple example that demonstrates the issue: DateSenderComponent is sending out the current date to be handled by its par ...

Incorporating the Vidyard embedded player within an Angular application

The Vidyard Portal provides an embed code that looks like this: <!-- The script tag should be placed in the head of your page if possible --> <script src="https://play.vidyard.com/embed/v4.js" type="text/javascript" async>&l ...

Issue with D3: Events not triggering transitions

I am currently working on creating a bar chart using D3 in Angular4. // Enter Phase this.chart.selectAll('.bar') .data(this.barData) .enter() .append('rect') .attr('class', 'bar'); // Update Phase let bars ...

Customizing the appearance of a form control in response to its value in Angular's Reactive

I have a unique query regarding formatting text related to formControl in an application where the formControls are created using FormBuilder and arrays of formControls. This inquiry involves retrieving the current value of a formControl and altering the ...

Unable to access due to CORS policy restriction in Ionic 5 Angular platform

Encountering an error, seeking guidance on the issue. Configuration has been done in proxy.conf.json. Headers with base url have been set in user.service.ts. import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions } fr ...

Error: The type '{ children: Element[]; className: string; }' cannot be assigned to the type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

My current setup involves using Next.js and TypeScript While working in Visual Studio Code, I encountered an error message stating Type error: Type '{ children: Element[]; className: string; }' is not assignable to type 'DetailedHTMLProps&l ...

React, redux, and redux observable are all essential tools for developing web applications. They

I am currently working on determining the type of a promise's resolve function. Here is a snippet of the code, or you can find it on GitHub: https://github.com/Electra-project/Electra-Desktop/blob/master/src/app/header/epics.ts export function getSt ...

A Error occurs if ReactQuill is used without defining the document object

Recently, I embarked on a journey with both next.js and ReactQuill. However, upon running yarn build, an unexpected obstacle arose: info Creating an optimized production build - info Compiled successfully - info Linting and checking validity of types - in ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Encountering a situation where the data retrieved from Firestore in Angular TypeScript is returning as

I am encountering an issue with retrieving the eventID value from my Events collection in Firestore. Although I am able to successfully display all the events in my app, I require the eventID for additional functionalities. As someone new to TypeScript an ...

The Angular2 component link imported in the core.module is not functioning properly

Adhering to the guidelines provided in the Angular style guide found at https://angular.io/styleguide#!#04-11, I have created a simple navigation setup. My app.component contains links like <a routerLink="hello">hello</a>, which work perfectly ...