Circular dependency has been detected when using the ESLint with TypeORM

Having two entity typeorm with a bi-directional one-to-one relationship:

Departament:

@Entity('Departament')
export default class Departament {
  @PrimaryGeneratedColumn()
  id: string;

  @Column()
  departament_name: string;

  @OneToOne(type => User, user => user.departament)
  @JoinColumn()
  user: User;

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  UpdatedAt: Date;
}

User:

@Entity('User')
export default class User {
  @PrimaryGeneratedColumn()
  id: string;

  @Column()
  name: string;

  @Column()
  last_name: string;

  @Column()
  email: string;

  @Column()
  login: string;

  @Column()
  password: string;

  @OneToOne(type => Departament, departament => departament.user)
  departament: Departament;
}

Here are my .eslintrc settings:

{
  "env": {
    "es6": true,
    "node": true,
    "jest": true
  },
  "extends": [
    "airbnb-base",
    "plugin:@typescript-eslint/recommended",
    "prettier/@typescript-eslint",
    "plugin:prettier/recommended"
  ],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint", "prettier"],
  "rules": {
    "prettier/prettier": "error",
    "no-new": "off",
    "no-underscore-dangle": "off",
    "class-methods-use-this": "off",
    "no-await-in-loop": "off",
    "import/prefer-default-export": "off",
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never"
      }
    ],
    "import/no-extraneous-dependencies": [
      "error",
      {
        "devDependencies": ["**/*.spec.ts", "src/utils/tests/*.ts"]
      }
    ],
    "no-useless-constructor": "off",
    "@typescript-eslint/no-unused-vars": [
      "error",
      {
        "argsIgnorePattern": "_"
      }
    ],
    "@typescript-eslint/no-useless-constructor": "error",
    "camelcase": "off",
    "@typescript-eslint/camelcase": "off"
  },
  "overrides": [
    {
      "files": ["*.js"],
      "rules": {
        "@typescript-eslint/no-var-requires": "off"
      }
    }
  ],
  "settings": {
    "import/extensions": [".ts", ".js"],
    "import/parsers": {
      "@typescript-eslint/parser": [".ts", ".js"]
    },
    "import/resolver": {
      "typescript": {
        "alwaysTryTypes": true
      }
    }
  }
}

Encountering these errors:

Error: dependency cycle detected.eslintimport/no-cycle

Specifically on (user and department)

And also this error:

'type' is defined but never used. Allowed unused args must match /_/u.eslint@typescript-eslint/no-unused-vars

I'm struggling to resolve this issue and unsure of the best course of action as I follow the TypeORM getting started guide.

Answer №1

Dealing with circular imports in programming can sometimes be a challenge, but it's usually possible to resolve them without causing too many issues. The eslint rule import/no-cycle is designed to catch any potential problems early on, which is definitely helpful. For more insights on this topic, check out a detailed Stack Overflow answer that recommends avoiding circular dependencies altogether.

If you're using TypeORM, there's an ongoing discussion in the repository that explores different solutions, each with its own pros and cons. Two commonly used solutions are entity schemas and string references. These approaches involve defining relations using strings and resolving them later when needed.

This method of handling circular dependencies is not unique to TypeORM; similar strategies can be found in other ORMs like SQLAlchemy in Python or ActiveRecord in Ruby on Rails. By retrieving entity classes or schemas from a registry using their names as strings, the need for explicit module imports to establish relationships is eliminated.

For example:

Entity schemas

Instead of defining entities using traditional class syntax and decorators, you can create instances of EntitySchema:

export const DepartmentEntity = new EntitySchema({
  name: "Department",
  columns: { /* omitted for brevity */ },
  relations: {
    user: {
      type: "one-to-one",
      target: "User"
    }
  }
})
export const UserEntity = new EntitySchema({
  ...
})

String references

This approach involves changing type functions and inverse side functions to strings and updating the relation attribute using import type:

...
...

Which one to choose?

The decision is yours to make. While the mechanics remain similar for both approaches, entity schemas are expected to become a core feature in future versions of TypeORM, offering better type safety compared to traditional classes. Consider your project requirements and preferences before deciding which solution suits you best.

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

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

When switching tabs, Ion-select should not reload the selected name

Whenever I switch tabs and then return to the previous tab in Ionic, the select field that was previously set becomes null, even though the page is still loading and the variable is populated. <ion-header color="primary"> <ion-navbar> &l ...

Adding dependency service to the parent class in Angular

I am working with classes parent and child. The child class is an extension of the parent class. I want to inject the injectable class service into the parent class since all instances of the child class will be using it as well. Can someone guide me on ...

What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem. To access the code, click here: https://stackblitz.com/edit/angular-ivy-87 ...

Troubleshooting problems encountered in Nest.js due to modifications made within a service.ts file

I'm currently working on a Nest.js project and here is the content of the automobile.service.ts file: import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Car } from './enti ...

What is the best approach to handling an undefined quantity of input FormControls within Angular?

I have a unique task in my Angular application where I need to collect an unspecified number of entries, such as names, into a list. My goal is to convert this list of names into an array. To facilitate this process, I would like to offer users the abilit ...

Sending input in a nested event listener

I am currently utilizing Highcharts for the purpose of showcasing an interactive map with custom countries. I have a specific requirement to enable the drilldown functionality, which involves clicking on a country to zoom in on another map displaying inter ...

Utilizing the get and set methods to alter the structure of a string, but encountering the issue where the set method is

Upon receiving a datetime through an HTTP request, I need to format it before utilizing it. To achieve this, I utilize the get and set methods in my code. However, I noticed that the set method is never invoked. This is how my component (AdminComponent) l ...

Angular: accomplish cascading requests to achieve desired outcomes

While exploring Angular rxjs operators, I came across a scenario where I need to send requests to the server that depend on each other. Currently, I have a modal window open and during the ngOnInit lifecycle hook, multiple requests are being sent, some of ...

The 'import.meta' meta-property can only be used with the '--module' set to 'es2020', 'esnext', or 'system'.ts(1343)

Whenever I attempt to utilize import.meta.url (as demonstrated in the Parcel docs), I am consistently met with the error message "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es ...

Steps for opening standalone angular2 and TypeScript project in visual studio: A guide to launching your project

What is the process for accessing an Angular2 and TypeScript project in Visual Studio without needing npm or Node.js? I require the ability to open the project on a computer that is not connected to a network. Many thanks ...

Ways to resolve: The JSX component does not contain any construction or call signatures

I've been grappling with a persistent issue regarding the creation of custom elements dynamically in React TypeScript. If you're curious, you can check out the question here. const generalButtons: MenuButton[] = [ { text: "New Cl ...

Is emitting a side effect event acceptable within an RxJS pipe?

Currently, I am utilizing RxJS within the context of an Angular application. Within my service, there is functionality to reinitialize the entire application with different settings as needed. @Injectable() class BootstrapService{ public initApplicatio ...

Please indicate the data type in Vue using Typescript

I'm currently struggling with Vue (3) + Typescript while attempting to specify a data property with a specific type. I have created a .d.ts file, but unfortunately, it hasn't helped. This is what I'm trying: import Modeler from 'bpmn-js ...

Confirming changes to checkbox values in Angular 2 prior to updating

My current challenge involves implementing a confirmation dialog in my application, and I'm feeling a bit unsure about the logic behind it. UserDetailsComponent.ts import { Component, OnInit, OnDestroy, ViewChild, Input, OnChanges, SimpleChange } f ...

I am encountering unexpected behavior with NextJS's getInitialProps function, as it is giving me a compiler error stating "varName not found on type {}"

I seem to be stuck on a simple syntax issue while working with NextJs. I am attempting to perform dynamic server-side fetches using the getInitialProps pattern. However, the compiler is unable to recognize the return of getInitialProps in the regular func ...

`How can TypeScript be used to designate the type of a variable within the useState hook?`

I defined a variable called 'text' and a hook named 'setText'. I'm using them to update the value of a form input field. How can I ensure that 'text' is always of type string? This is what I attempted: interface TextInt ...

Typescript throwing error TS2307 when attempting to deploy a NodeJS app on Heroku platform

Encountering an error when running the command git push heroku master? The build step flags an error, even though locally, using identical NodeJS and NPM versions, no such issue arises. All automated tests pass successfully without any errors. How can this ...

Determine the accurate data type while iterating through a for loop

I am facing an issue where I have around 40 unique actions defined, all with the same parameters except for each being provided with a different schema which is causing the problem type ActionName = 'replaceText' | 'replaceImage'; type ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...