Search code examples
typescripteslinttypescript-eslint

eslint member-ordering trap - whichever declaration comes first causes an error


I've got this code:

export class RouteParamsService {
  private routeParamsChangeSource = new ReplaySubject<Params>() // let's call this line 1
  routeParamsChange$ = this.routeParamsChangeSource.asObservable() // let's call this line 2
  ... etc
}

If I put line 1 before line 2 I get the error:

@typescript-eslint/member-ordering Member routeParamsChange$ should be declared before all private instance field definitions

If I put line 2 before line 1 I get the error:

Property routeParamsChangeSource is used before its initialisation

I understand both errors and why I am getting them. However, is there a rule that will relax the rules BUT ONLY when you end up in a trap like this? I know I can do eslint-disable-line @typescript-eslint/member-ordering but I don't want to have to do this every time I hit this issue (which I am hitting a lot).

I also DO NOT want to make routeParamsChangeSource public.

Any ideas?


Solution

  • The @typescript-eslint/member-ordering lint rule does not currently understand dependencies between fields.

    As you can understand - this sort of dependency creates a complex ordering problem, which nobody from the community has yet been motivated enough to solve.

    You can see the issue tracking it here: https://github.com/typescript-eslint/typescript-eslint/issues/2882

    The project welcomes contributions - if this is a problem that is important to you.


    As for actual workarounds or fixes.

    Disable comments are a good temporary measure.

    Another alternative is to move the dependencies into the constructor:

    export class RouteParamsService {
      private routeParamsChangeSource = new ReplaySubject<Params>();
      routeParamsChange$;
    
      constructor() {
        this.routeParamsChange$ = this.routeParamsChangeSource.asObservable();
      }
    }