Home > database >  How to assign a 'get' function to a variable in a model. Typescript
How to assign a 'get' function to a variable in a model. Typescript

Time:06-11

code below:

export class User {

constructor(

  public Id: number,
  public Prefix: string,
  public FirstName: string,
  public LastName: string,
  public MiddleInitial: string,
  public FullName: string = function() {
    return FirstName   ' '   LastName;
  },
){ }
}

The fullname variable is throwing an error, any help/other approaches would be appreciated.

CodePudding user response:

You state that FullName should expect string, but you try to assign function to it. As you want to assign to FullName value that will be a composition of two constructor params, you have to declare FullName as a User class field, and assign value to it in constructor body:

class User {
  public FullName: string;
  
  constructor(
    public Id: number,
    public Prefix: string,
    public FirstName: string,
    public LastName: string,
    public MiddleInitial: string,
  ) { 
    this.FullName = FirstName   ' '   LastName;
  }
}

CodePudding user response:

It sounds like you just want a property getter on your class.

Something like:

class User {
    constructor(
        public FirstName: string,
        public LastName: string,
    ){}

    get FullName(): string {
        return this.FirstName   ' '   this.LastName;
    }
}

console.log(new User('A', 'B').FullName) // 'A B'

Playground

  • Related