Is there a circular dependency issue with ManyToMany relationships in Typescript TypeORM?

Below are the entities I have defined. The Student entity can subscribe to multiple Teachers, and vice versa - a Teacher can have many Students.

import { PrimaryGeneratedColumn, Column, BeforeInsert, BeforeUpdate } from "typeorm"
/*
* Adhering to the Data Mapper pattern: https://typeorm.io/active-record-data-mapper
*/
export abstract class EntityBase {
    @PrimaryGeneratedColumn()
    public id: number
    @Column()
    public created: Date
    @Column()
    public modified: Date
    @BeforeInsert()
    updateDates () {
        this.created = new Date();
        this.modified = new Date();
    }
    @BeforeUpdate()
    updateModifiedDate () {
        this.modified = new Date();
    }
}
import { Entity, Column, ManyToMany, JoinTable } from "typeorm"
import { EntityBase } from "./EntityBase"
import { Teacher } from "./Teacher"
@Entity()
export class Student extends EntityBase {
    @Column({ length: 256 })
    public firstName: string

    @Column({ length: 256 })
    public lastName: string

    @Column({ unique: true, length: 256 })
    public email: string

    @Column()
    public isSuspended: boolean

    @ManyToMany((type) => Teacher, (teacher) => teacher.students)
    @JoinTable()
    public teachers: Teacher[]

    constructor(first: string, last: string, email: string, isSuspended?: boolean) {
        super();
        this.firstName = first;
        this.lastName = last;
        this.email = email;
        this.isSuspended = isSuspended ?? false;
        this.teachers = [];
    }
}
import { Entity, Column, JoinTable, ManyToMany } from "typeorm"
import { EntityBase } from "./EntityBase"
import { Student } from "./Student"
@Entity()
export class Teacher extends EntityBase {
    @Column({ length: 256 })
    public firstName: string

    @Column({ length: 256 })
    public lastName: string

    @Column({ unique: true, length: 256 })
    public email: string

    @ManyToMany((type) => Student, (student) => student.teachers)
    @JoinTable()
    public students: Student[]

    constructor(first: string, last: string, email: string) {
        super();
        this.firstName = first;
        this.lastName = last;
        this.email = email;
        this.students = [];
    }
}

Could this potentially lead to circular loading? What strategies can be implemented to enhance or avoid this scenario?

Answer №1

There is no risk of a circular dependency error in this scenario. The concept of the `class` has two distinct aspects - as a type and as a value. While the types of Teacher and Student may reference each other in a circular manner, when they are used as constants, there is no direct connection between them during loading (at import time). This separation is made possible by delaying the value reference like in the example (type) => Teacher.

teacher: Teacher; // Here, Teacher is being used as a type, so circular references are not an issue.

() => Teacher; // In this case, Teacher is treated as a constant value, causing potential problems if accessed directly without using the delay function.

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

A step-by-step guide on leveraging swagger-autogen in TypeScript applications

Is it possible to integrate the swagger-autogen module into a Typescript project? I have attempted multiple methods, but have been unsuccessful. The error message "Failed" keeps appearing when using a swagger.js file: const swaggerAutogen = require("swagge ...

Challenges with date formatting arise for Spanish speakers when the date returns as NaN or an Invalid

I have been working on an Angular app Objective: My aim is to allow users to input dates in Spanish format (DD/MM/YYYY) and display them as such, while converting them back to English format when saving the data to the Database. Issue: One problem I enco ...

Why does TypeScript struggle to accurately deduce the return type when provided with certain parameter values?

I have a function that uses a switch case to return different results depending on the input. The function, called "getTimeAgo," takes in two parameters: "date" (which can be either a Date object or a string) and "mode" (which can only be either "days" or ...

Why isn't my event handler triggering when working with TypeScript services and observables?

I am currently working on a project in Angular 2 where I am incorporating observables and services in typescript. However, I have encountered an issue where the event handler in my observable is not being triggered. Below is the code snippet: The Service ...

Unit testing in Typescript often involves the practice of mocking

One challenge with mocking in Typescript arises when dealing with complex objects, as is the case with any strongly-typed language. Sometimes additional elements need to be mocked just to ensure code compilation, such as using AutoFixture in C#. In contras ...

When running the command ng build --prod, it seems that the module for class X cannot be determined. To resolve this issue, make sure to include

I'm encountering an issue while trying to develop my Angular 5 application. The error message reads: Cannot determine the module for class ThreadListTabsComponent in /home/brightwater/Differ/src/app/thread-lists/thread-lists.component.ts! Add T ...

Creating a customized Axios instance in Typescript can provide more flexibility and control over

I am looking to create an API with a customizable instance using Axios. Ideally, I want to be able to use a basic instance like this: api.get("url")... In addition, I would like to have the flexibility to add dynamic bodies and access them using something ...

Transforming Boolean data types into text within an Angular 2 client-side application

Query I'm currently working on retrieving data from an API and displaying it in a table. One of the columns includes a status attribute that returns either true or false values. However, I would like to display "Active" or "Block" instead on the clie ...

Creating a function that operates according to the input parameter

Imagine a scenario where I am working with the following JS function: function fetchValue(keyName) { return x => x[keyName]; } Is it possible to define fetchValue in such a way that Typescript's type inference automatically determines the outp ...

Is it possible to define a variable within an array declaration?

I am trying to construct an array for the week, with each element being an instance of my "work hours" class. However, when attempting to define them within the array directly, I encounter an error. Upon inspecting the JS file, I noticed that the array is ...

What is the most effective method for identifying duplicate values in a multidimensional array using typescript or javascript?

I have a 2D array as shown below: array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ] I am looking to compare the values in the array indexes to check for duplicates. For example array[0] = [1,1]; array[1] = [1,2]; array[2] = [1,1]; We can see that ...

Injecting styles haphazardly using styled-components

When populating a grid with various controls such as an up-down counter and a text box, I currently inject styles into the cls member. For example, classes like wide-input and narrow-input: render(): ReactNode { const input: CellItem[] = [ { i ...

Develop a directive for transforming data

In my latest project, I am looking to develop a LoaderDirective that can fetch an observable, display a spinner while loading the data, and then switch to showing the actual data once loaded. I also want it to expose the loaded data using the 'as&apos ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt: Presentation.svelte <script lang="ts"> export let slides; </script> {#each slides as slide} & ...

Setting the title of a document in Angular 5 using HTML escaped characters

It seems like a simple problem, but I can't seem to find an easy solution. Currently, I am using the Title service to add titles to my documents and everything is working fine. You can check out the documentation here: https://angular.io/guide/set-doc ...

Effortless transfer of a module from one TypeScript file to another

I'm facing an issue with importing classes from one .ts file to another .ts file. Here is the structure of my project: https://i.sstatic.net/gZM57.png I'm attempting to import print.ts into testing.ts This is how my tsconfig.json appears: ht ...

Guide on incorporating secondary endpoints to develop an API for an Angular library

Challenge: I recently developed a customized UI library using ng-packagr, where I exported unique components along with some model classes. Issue: While the import statement functions correctly for the exported components in my main project, it fails to ...

What prevents TypeScript from allowing an async function to return a combination of type T or Promise<T>?

During the development of my API in typescript, I encountered a situation where some controller actions can be synchronous while others cannot. To address this issue, I decided to specify a response type as follows: type ActionResult =IHttpActionResult | ...