typeorm: Typesafe entity initialization does not work with TypeOrm 0.3.6

Issue Description

In issue #3903, the last comment recommends to use a constructor to prevent errors like

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

when using TypeScript’s strict mode. This was made possible one year ago when #7770 got merged. However, back then, the latest version of TypeOrm was 0.2.x. With TypeOrm 0.3.x, the use of constructors does not work.

Expected Behavior

It should be possible to use constructors with TypeOrm because this is the only type-safe way of initializing an object’s attributes.

Actual Behavior

When initializing a database connection (regardless of whether .initialize() or .connect() is called because these are aliases), function validate() in EntityMetadataValidator.ts is inevitably reached. This function inevitably runs the following code:

const entityInstance = entityMetadata.create(undefined, {
    fromDeserializer: true,
});

This leads to an error like the following being thrown:

/usr/src/app/src/commons/entities/event.ts:44
    this.address = params.address;
                          ^
TypeError: Cannot read properties of undefined (reading 'address')
    at new Event (/usr/src/app/src/commons/entities/event.ts:44:27)
    at EntityMetadata.create (/usr/src/app/src/metadata/EntityMetadata.ts:563:23)
    at EntityMetadataValidator.validate (/usr/src/app/src/metadata-builder/EntityMetadataValidator.ts:172:47)
    at /usr/src/app/src/metadata-builder/EntityMetadataValidator.ts:43:18
    at Array.forEach (<anonymous>)
    at EntityMetadataValidator.validateMany (/usr/src/app/src/metadata-builder/EntityMetadataValidator.ts:42:25)
    at DataSource.buildMetadatas (/usr/src/app/src/data-source/DataSource.ts:682:33)
    at async DataSource.initialize (/usr/src/app/src/data-source/DataSource.ts:241:13)

Steps to Reproduce

Having any entity that uses a constructor while using the latest version of TypeOrm (0.3.6) will trigger the bug while the database connection is being established via .initialize(). Example entity:

import {Column, Entity, Index} from 'typeorm';

@Index('examples_pkey', ['name'], {unique: true})
@Entity('examples', {schema: 'public'})
export class Example {
  @Column('text', {primary: true, name: 'name'})
    name: string;

  constructor(params: {name: string}) {
    this.name = params.name;
  }
}

My Environment

Dependency Version
Operating System Manjaro
Node.js version v16.9.1
Typescript version 4.6.2
TypeORM version 0.3.6

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql no
aurora-postgres no
better-sqlite3 no
cockroachdb no
cordova no
expo no
mongodb no
mysql no
nativescript no
oracle no
postgres yes
react-native no
sap no
spanner no
sqlite no
sqlite-abstract no
sqljs no
sqlserver no

Are you willing to resolve this issue by submitting a Pull Request?

  • ✖️ Yes, I have the time, and I know how to start.
  • ✅ Yes, I have the time, but I don’t know how to start. I would need guidance.
  • ✖️ No, I don’t have the time, but I can support (using donations) development.
  • ✖️ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 17

Most upvoted comments

set "strict"= false in tsconfig.json

"strictPropertyInitialization": false is probably the cleanest solution

As I understand from @mishabruml repos you need to set a constructor that will initialize your variables but you will skip this step on build with option entitySkipConstructor of the datasource.

src/entities/example.ts

type ExampleRow = { name: string; age: number; isMale: boolean };

@Entity('examples', { schema: 'public' })
export class Example {
  @Column('text', { primary: true, name: 'name' })
  name;

  @Column('int')
  age;

  @Column('boolean')
  isMale;

  // Set a constructor, avoiding TS errors
  constructor({ age, name, isMale }: ExampleRow) {
    this.name = name;
    this.age = age;
    this.isMale = isMale;
  }
}

src/datasource.ts

export const dataSource = new DataSource({
	type: "postgres",
	host: "",
	port: 55001,
	username: "",
	password: "",
	database: "postgres",
	entities: [Example],
	migrations: [],
	synchronize: false,
	logging: false,
	entitySkipConstructor: true, // Indicates that TypeORM will skip constructors when deserializing entities from the database
});

set "strict"= false in tsconfig.json

using js itself is better in this case I think

It’s been a while since I was looking at this but I think the skipEntityConstructor means typedorm does not attempt to run the constructor function on declaration of the class. It will still be run on new Entity({arg: foo})

I have verified that this works. I ran the code here against a local Postgres database and all worked as expected 👍

https://github.com/mishabruml/typeorm-playground/blob/master/src/index.ts#L15

@mishabruml Thank you for your suggestion. However, this does not solve the problem discussed in this issue. It merely addresses the comfort aspect of a constructor. This issue is about the type safety aspect of a constructor. As there is no guarantee that that custom construct() function is called before the object is used, typescript views the attributes as non-initialized, leading to error messages like

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

in strict mode.