TypeORM OneToMany causes "ReferenceError: Cannot access '<Entity>' before initialization"

In tsconfig, setting the target to "esnext" and module to "commonjs" fixed the issue for me

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "types": ["node", "jest"],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "target": "esnext"
  },
  "include": ["**/*.ts"]
}

I solved this by using autoLoadEntities: true when loading the TypeORM config to NestJS. Note that this is a NestJS extra, so if you are using ormconfig.json this property won't be applied.

autoLoadEntities documentation here: https://docs.nestjs.com/techniques/database#auto-load-entities

UPDATE 04/10/2020

I kept having the same issue with relations. Another solution I found, even if it breaks some standards is to add all the Entities into 1 file. Export them there and import them where needed.

Keep in mind that the order in which the classes are declared matters.


You can accomplish the same thing as @jdruper by using a barrel file. If you don't have a paths property in your tsconfig.json, add one under compilerOptions that looks something like this:

"paths": {
   "@entities":["app/src/entities/index.ts"]
}

Put all your entity classes in the entities folder, create the index.ts file and add export statements in the index.ts file:

export * from './user.entity';
export * from './habit.entity';

Make sure the export statements appear in the required order. Your imports would then look like this.

import { User, Habit } from '@entities';

You can search for typescript barrel file for more information on how to work with barrel files.

If you're using NX you can make an entities lib and accomplish the same thing.

It will probably mean having to move all your entity files together and updating the imports in your modules and services. Maybe not exactly ideal, but I would prefer that over having them all in one file.