Search code examples
typescripttypeorm

How to add a helper method to a typeORM entity?


I'm trying to add a helper method to one of my Entity classes but I'm getting an error message. My entity:

import { Entity, PrimaryColumn, Column } from 'typeorm'

@Entity('accounts')
class Account {
  @PrimaryColumn()
  username: string

  @Column({ name: 'firstname' })
  firstName: string

  @Column({ name: 'lastname' })
  lastName: string

  public fullName() : string {
    return `${this.firstName} ${this.lastName}`
  }
}

When I try to call account.fullName() I get the following error message:

"account.fullName" is not a function

What am I getting wrong?


Solution

  • Add the get keyword and call it using property syntax.

    import { Entity, PrimaryColumn, Column } from 'typeorm'
    
    @Entity('accounts')
    class Account {
      @PrimaryColumn()
      username: string
    
      @Column({ name: 'firstname' })
      firstName: string
    
      @Column({ name: 'lastname' })
      lastName: string
    
      public get fullName() : string {
        return `${this.firstName} ${this.lastName}`
      }
    }