typeorm: "ReferenceError: Cannot access 'Entity' before initialization" when running migrations
Issue type:
[x] question [x] bug report? [ ] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[x] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[ ] latest
[ ] @next
[x] 0.2.24
Steps to reproduce or a small repository showing the problem:
Getting the following error when trying to add relations and then generate migrations:
Error during migration generation:
ReferenceError: Cannot access 'B' before initialization
Even with this incredibly simple example (classes in the same file):
@Entity()
export class A extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
public id!: string;
@OneToOne(
() => B,
b => b.a
)
public b!: B;
}
@Entity()
export class B extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
public id!: string;
@OneToOne(
() => A,
a => a.b
)
@JoinColumn()
public a!: A;
}
This code compiles ~and runs~ fine, I just cannot run migrations for it.
Edit: I get the same error when starting my server.
My orm config is something like:
import { ConnectionOptions } from 'typeorm';
import * as entities from './entities';
export const ORM_CONFIG: ConnectionOptions = {
type: 'postgres',
url: process.env.DATABASE_URL,
entities: Object.values(entities),
logging: true,
};
I had to import my entities because I haven’t yet been able to get typeorm to pick them up at all when using paths; for example, ./entities/**/*.ts.
And here’s my tsconfig:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"pretty": true,
"sourceMap": true,
"skipLibCheck": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"jsx": "react",
"target": "es6",
"moduleResolution": "node",
"typeRoots": ["./node_modules/@types/", "./@types/"]
},
"include": ["./src/", "./@types/"]
}
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 8
- Comments: 15
For anyone who encountered this issue,
import { Relation } from 'typeorm'then wrap you entity with Relation LikeRelation<Entity>Ooh solution exists! https://github.com/typeorm/typeorm/issues/4190
Okay, this now appears to work if I put the entities into separate modules and change my orm config to:
But this isn’t ideal. Can I not have my entities in the same file?
Hello @JakeSidSmith, I had the same issue and was able to find the solution by organizing my code. Indeed, if your entities are in the same .ts file, you must be careful to declare the child entities (nested in the others) before. For example, in your case, you will have to declare class B first before class A It works fine for me …