question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is it possible to initialize an entity with a config object?

See original GitHub issue

Issue type:

[x] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [ ] postgres [ ] cockroachdb [x] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[ ] latest [ ] @next [x] 0.2.15

Steps to reproduce or a small repository showing the problem:

I modified the sample which comes with:

typeorm init --name MyProject --database sqlite

In the original setup a user is created like this:

const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.age = 25;

Unfortunately this doesn’t work well when you use "strict": true in your tsconfig.json because it will throw the following error:

error TS2564: Property ‘firstName’ has no initializer and is not definitely assigned in the constructor.

To avoid the above error I tried passing an object to User:

const user = new User({
  firstName: "Timber",
  lastName: "Saw",
  age: 25
});

I also updated the User.ts file:

import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  age: number;

  constructor(params: { firstName: string, lastName: string, age: number }) {
    this.id = 0;
    this.firstName = params.firstName;
    this.lastName = params.lastName;
    this.age = params.age;
  }
}

When I now run the program, I receive the following error:

TypeError: Cannot read property ‘firstName’ of undefined at new User (D:\Temp\MyProject\src\entity\User.ts:20:29) at EntityMetadata.create (D:\Temp\MyProject\src\metadata\EntityMetadata.ts:500:19) at EntityMetadataValidator.validate (D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:111:47) at D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:44:56 at Array.forEach (<anonymous>) at EntityMetadataValidator.validateMany (D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:44:25) at Connection.buildMetadatas (D:\Temp\MyProject\src\connection\Connection.ts:508:33) at Connection.<anonymous> (D:\Temp\MyProject\src\connection\Connection.ts:189:18) at step (D:\Temp\MyProject\node_modules\tslib\tslib.js:133:27) at Object.next (D:\Temp\MyProject\node_modules\tslib\tslib.js:114:57)

How come that firstName is undefined? In my code I never call new User without a configuration object.

Is TypeORM doing some magic in the background and calls new User() (without giving it a parameter)?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

19reactions
abingoalcommented, Mar 27, 2019

When you use "strict": true in your tsconfig.json, you must modify your entity like this:

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  firstName!: string;

  @Column()
  lastName!: string;

  @Column()
  age!: number;
}

just add a bang sign (!).

8reactions
bennycodecommented, Oct 16, 2019

@vlapo I tested with typeorm v0.3.0-alpha.24 and it works now. Thank you very much! 🥳

Here is my full test code for people finding this issue:

initDatabase.ts

import 'reflect-metadata';
import {Connection, createConnection} from 'typeorm';
import {SqliteConnectionOptions} from 'typeorm/driver/sqlite/SqliteConnectionOptions';
import {PostgresConnectionOptions} from 'typeorm/driver/postgres/PostgresConnectionOptions';
import {User} from './entity/User';

export default function initDatabase(): Promise<Connection> {
  const localhost: SqliteConnectionOptions = {
    database: 'test.db3',
    type: 'sqlite'
  };

  const production: PostgresConnectionOptions = {
    type: 'postgres',
    url: process.env.DATABASE_URL
  };

  const connectionOptions = (process.env.NODE_ENV === 'production') ? production : localhost;

  Object.assign(connectionOptions, {
    entities: [
      User
    ],
    logging: false,
    migrations: [
      'src/migration/**/*.ts'
    ],
    subscribers: [
      'src/subscriber/**/*.ts'
    ],
    synchronize: true,
  });

  return createConnection(connectionOptions);
};

User.ts

import {BaseEntity, Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  age: number;

  constructor(params: { firstName: string, lastName: string, age: number }) {
    super();
    this.id = 0;
    this.firstName = params.firstName;
    this.lastName = params.lastName;
    this.age = params.age;
  }
}

index.ts

import initDatabase from "./initDatabase";
import {User} from "./entity/User";

(async () => {
  await initDatabase();
  const user = new User({
    firstName: "Timber",
    lastName: "Saw",
    age: 25
  });
  await user.save();
})();
Read more comments on GitHub >

github_iconTop Results From Across the Web

java - What is the correct way to initialize collection of an entity ...
This is the best way to initialize collection valued properties of newly instantiated (non-persistent) instances. When you make the instance ...
Read more >
Object and Collection Initializers - C# Programming Guide
Object initializers in C# assign values to accessible fields or properties of an object at creation after invoking a constructor.
Read more >
Database Initialization Strategies in EF 6 Code-First
CreateDatabaseIfNotExists: This is the default initializer. As the name suggests, it will create the database if none exists as per the configuration. However, ......
Read more >
A Guide to Java Initialization - Baeldung
Simply put, before we can work with an object on the JVM, it has to be initialized. In this tutorial, we'll examine the...
Read more >
Mapping configuration to objects - Quarkus
In certain situations it may not be possible to correctly initialize a config mapping. For instance, if the mapping requires values from a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found