簡體   English   中英

為什么我不能在 typeorm 中更改實體的構造函數

[英]Why can't I change the entity's constructor in typeorm

我是 Typeorm 和 typescript 的新手。我現在一直這樣使用它:

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()

現在效果很好。 我使用 Object.assign 是因為如果我從具有 30 個字段的用戶那里收到它作為輸入,這比我必須手動完成要方便得多。 但是,我希望能夠通過將它包含在構造函數中來進一步簡化它,這樣我就不必每次都這樣做了:

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()

我本以為它可以毫無問題地工作,但是我在let actors = Actor.find()行中得到了一個我似乎無法理解的非常奇怪的問題:

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

我假設這是由於構造函數中 arguments 的數量發生了變化,但它不像一個接口可以指示構造函數應該是什么樣子所以我有點迷茫為什么會發生這種情況以及我在那里誤解了什么

您收到一個錯誤,因為您的 Actor 實體現在需要一個 argument ,但是 TypeORM 不會將任何 arguments 傳遞給它(這是不合理的,想象一下期待蛋糕然后沒有得到蛋糕;多么可悲)。 您可以通過將參數設為可選(默認為{} )來解決這個問題:

export class Actor extends BaseEntity {

  constructor(obj = {}) {
    super()
    Object.assign(this, obj)
  }

  @Column()
  name: string

  @Column()
  age: number

}

但無論如何,您真的不應該更改實體 class。也許您可以嘗試使用構建器的想法?

new ActorBuilder().setName(...).setAge(...).build() // returns Actor

或助手 function:

createActor({ ... }) // returns Actor

最好不要修改實體 class。您真的不知道 TypeORM 在幕后做了什么(當然,除非您是貢獻者:D)所以我會按原樣保留實體 class。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM