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.
CodePudding user response:
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)