Search code examples
typescriptmodel

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


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.


Solution

  • 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;
      }
    }