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

前端 未结 5 1067
陌清茗
陌清茗 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-03 17:30

    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.

提交回复
热议问题