I had this issue, and I solved it in two ways that I will explain in below.
First Solution:
interface Person {
firstName?: string
lastName?: string
readonly age?: number
fullName(): string
}
class User implements Person {
private _firstName: string | undefined
private _lastName: string | undefined
constructor(public firstName?:string,public lastName?: string, readonly age?: number){
this._firstName = firstName
this._lastName = lastName
delete this.firstName;
delete this.lastName;
}
fullName(): string {
return this._firstName + " " + this._lastName;
}
introduce(): string{
return this.fullName() + " is " + this.age;
}
}
let Reza= new User("Reza","Hadipour",32);
console.log(Reza.fullName()); // -> Reza Hadipour
console.log(Reza.introduce()); // -> Reza Hadipour is 32
console.log(Reza.firstName); // -> Undefined
In the above code, _lastName and _firstName are private and work correctly, but the problem occurs once you want to delete public properties (this.firstName and this.lastName), The delete method needs optional operand, so to solve this I had to define lastName and firstName as optional properties which you can see in interface and constructor implementations. The biggest problem in this solution is the optional property lets users ignore them which should cause problems in the next. because of optional public properties, I have to define private properties with two string and undefined types.
private _firstName: string | undefined
private _lastName: string | undefined
this is so unreliable implementation!! so, I suggest the second way.
Second Solution
interface Person {
firstName: string
lastName: string
readonly age: number
fullName(): string
}
class User implements Person {
private _firstName: string
private _lastName: string
constructor(public firstName:string,public lastName: string, readonly age: number){
this._firstName = firstName
this._lastName = lastName
this.firstName = this.lastName = "";
}
fullName(): string {
return this._firstName + " " + this._lastName;
}
introduce(): string{
return this.fullName() + " is " + this.age;
}
}
let Reza = new User("Reza","Nikpour",35);
console.log(Reza.fullName()); // -> Reza Nikpour
console.log(Reza.introduce()); // -> Reza Nikpour is 35
console.log(Reza.firstName); // ->
In the second code, I just assets empty value into the this.firstName and this.lastName in the constructor instead of deleting them.