Is it possible to initialize an entity with a config object?
See original GitHub issueIssue 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:
- Created 4 years ago
- Reactions:2
- Comments:7 (3 by maintainers)
Top GitHub Comments
When you use
"strict": true
in yourtsconfig.json
, you must modify your entity like this:just add a bang sign (!).
@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
User.ts
index.ts