How to define a private property when implementing an interface in Typescript?

前端 未结 5 1070
陌清茗
陌清茗 2021-02-03 17:05

I\'m using TypeScript in my project and I have come across an issue. I\'m defining an interface like this:

interface IModuleMenuItem {
    name: string;
}
         


        
5条回答
  •  醉话见心
    2021-02-03 17:44

    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. As such you can't do what you want with an interface.

    If you are 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";
        }
    }
    

提交回复
热议问题