How to define a private property when implementing an interface in Typescript?
Interfaces define "public" contracts and as such it doesn't make sense to have protected
or private
access modifier on interfaces, which are more of a, let's call it, implementation detail. For that reason you can't do what you want with an interface.
If you want to make the property read-only to consumers, but overridable in a subclass then you can do something like this:
interface IModuleMenuItem {
getName(): string;
}
class ModuleMenuItem implements IModuleMenuItem {
private name;
public getName() {
return name;
}
protected setName(newName : string) {
name = newName;
}
}
I think in TypeScript 2.0 (not out yet) you will be able to use the readonly
access modifier if you were after initialization-time readonly field - https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html
interface IModuleMenuItem {
readonly name : string;
}
class ModuleMenuItem implements IModuleMenuItem {
public readonly name : string;
constructor() {
name = "name";
}
}
In case of having private fields in class, you need to introduce setter and get methods for that field like so:
export class Model {
private _field: number;
get field(): number {
return this._field;
}
set field(value: number) {
this._field= value;
}
}
And then create the interface as usual (We can not use private modifier for interface fields) like so:
export interface IModel {
field: number;
}
Then implement it to our class like so:
export class Model implements IModel {
...
}
TypeScript will understand that this model is implemented correctly the interface as we have introduced set and get method.
I think you may do it like this
interface IModuleMenuItem{
name: string
}
class ModuleMenuItem implements IModuleMenuItem {
private _name: string;
constructor() {
_name = "name";
}
get name(){
// your implementation to expose name
}
set name(value){
// your implementation to set name
}
}