Sometimes, we want to define a private property when implementing an interface in TypeScript.
In this article, we’ll look at how to define a private property when implementing an interface in TypeScript.
How to define a private property when implementing an interface in TypeScript?
To define a private property when implementing an interface in TypeScript, we can add private properties into the class that implements the interface.
For instance, we write
interface IModuleMenuItem {
getName(): string;
}
class ModuleMenuItem implements IModuleMenuItem {
private name;
public getName() {
return name;
}
protected setName(newName: string) {
name = newName;
}
}
to add the name
private variable into the ModuleMenuItem
class.
All interface properties must be public.
Conclusion
To define a private property when implementing an interface in TypeScript, we can add private properties into the class that implements the interface.