Search code examples
javascriptangularjstypescriptencapsulation

Typescript + Angular expose service method


I'm using typescript and angular on a project. When i want to expose service's method i do the following :

export class MyService implements IService {

    //Public method
    public myMethod: Function;

    public constructor() {

        this.myMethod= this._myMethod;

    }

    private _myMethod(): void {
       //...
    }

When i work on service which get many method, i don't have to scroll to see method's definition so that's great. But now when i'm using my service's method in another service or controller, i can't see signature of my method... So i'm loosing typescript advantages...

Any idea ?

Thanks.


Solution

  • The simple answer is that you need to give your function definition a signature

    class MyService {
        public myMethod: () => void; //don't use Function
    
        constructor() {
            this.myMethod = this.myMethod;
        }
    
        _myMethod = () => {
    
        }
    

    }

    However a better approach is to define an interface:

    interface IMyService extends IService {
        myMethod: () => void;
    }
    
    class MyService implements IMyService {
        constructor() {
    
        }
    
        myMethod = () => {
    
        }
    }