I'm fairly new to Typeorm and typescript. I've been using it like so for now :
export class Actor extends BaseEntity {
@Column()
name: string
@Column()
age: number
}
let actor = new Actor()
Object.assign(actor, { name: "John Doe", age: 50 })
await actor.save()
let actors = Actor.find()
It work great for now. I use Object.assign because if I receive it as input from the user with 30 fields, it's much more convenient than if I had to do it manually. However, I was hoping to be able to simplify it further by including it in the constructor so I don't have to do it everytime :
export class Actor extends BaseEntity {
constructor(obj){
super()
Object.assign(this, obj)
}
@Column()
name: string
@Column()
age: number
}
let actor = new Actor({ name: "John Doe", age: 50 })
await actor.save()
let actors = Actor.find()
I would have expected it to work without issues but I get a very weird one that I can't seem to understand on the let actors = Actor.find()
line :
The 'this' context of type 'typeof Actor' is not assignable to method's 'this' of
type '(new () => Actor) & typeof BaseEntity'.
Type 'typeof Actor' is not assignable to type 'new () => Actor'.
Types of construct signatures are incompatible.
Type 'new (obj: any) => Actor' is not assignable to type 'new () => Actor'.ts
I'm assuming it's due to the amount of arguments changing in the constructor but it's not like an interface can indicates what the constructor should look like so I'm a bit lost as why this happens and what do I misunderstand there
CodePudding user response:
You're getting an error because your Actor entity now expects one argument, but TypeORM won't pass any arguments to it (which is unsound, imagine expecting a cake and then not getting a cake; how sad). You can probably get around this by making the parameter optional (defaulting to {}
):
export class Actor extends BaseEntity {
constructor(obj = {}) {
super()
Object.assign(this, obj)
}
@Column()
name: string
@Column()
age: number
}
but in any case you really shouldn't be changing the entity class. Maybe you could play around with the idea of a builder instead?
new ActorBuilder().setName(...).setAge(...).build() // returns Actor
or a helper function:
createActor({ ... }) // returns Actor
It's probably best not to modify the entity class. You don't really know what TypeORM is doing under the hood (unless you are a contributor, of course :D) so I would keep the entity class as-is.