Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript class getters are not returning any data

I am trying to create a Typescript class that has read-only properties based on other properties in the class. The properties in question are the firstLastName and lastFirstName properties. Here is my class:

export interface IMember {
  id: string;
  firstName: string;
  lastName: string;
  active: boolean;
  readonly firstLastName: string;
  readonly lastFirstName: string;
}

export class Member implements IMember {
  id: string;
  firstName: string;
  lastName: string;
  active: boolean;
  get firstLastName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  get lastFirstName(): string {
    return `${this.lastName}, ${this.firstName}`;
  }
}

I have tried manually creating a new member object and assigning the four required properties, and I also tried creating member objects from JSON. In both cases, the code acts like the firstLastName and lastFirstName properties aren’t there at all. Also, when creating the object manually, I have to mark the type as Partial, or the compiler complains that the object is missing properties (firstLastName and lastFirstName). This seems so straightforward, and I found another question here that basically showed exactly what I’m doing as the solution, but it’s just not working for me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Mb You have to initialize properties.
This code works in the playground:

interface IMember {
  id: string;
  firstName: string;
  lastName: string;
  active: boolean;
  readonly firstLastName: string;
  readonly lastFirstName: string;
}

class Member implements IMember {
  id: string = "";
  firstName: string = "first";
  lastName: string = "last";
  active: boolean = false;
  get firstLastName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  get lastFirstName(): string {
    return `${this.lastName}, ${this.firstName}`;
  }
}

const m = new Member

console.log(m.firstLastName)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading