skip to Main Content

I have the following code working but and it currently looks like this:

import { OtherClass } from "other-class"

class VeryLongClass {

}

OtherClass.run(VeryLongClass);

But I want it to look like this:

import { OtherClass } from "other-class"

OtherClass.run(VeryLongClass);

class VeryLongClass {

}

For visibility and readability, I want to have the call to the run function at the top of the class. It needs to be called. But if I move it to the top of the class I get the error from Typescript:

Class 'VeryLongClass' used before its declaration.ts(2449)
classes.ts(6, 14): 'VeryLongClass' is declared here.

I know the technical reasons why this is not correct but I also know there are language features like variable hoisting. So

For this project, it’s important to have this call made, OtherClass.run(VeryLongClass) but when it is at the end of the class file the call to this function is sometimes forgotten and and on long files more difficult to confirm.

2

Answers


  1. You can use a decorator:

    function doSomething(
      target: typeof VeryLongClass,
      context: ClassDecoratorContext<typeof VeryLongClass>
    ): void | typeof VeryLongClass {
      // Do something here
      return target;
    }
    

    And apply it as follows:

    @doSomething
      class VeryLongClass {
    }
    

    The decorator is applied during the declaration.
    It might not be what you need but is the only option I could think about.

    Login or Signup to reply.
  2. I’d consider reorganising your code to isolate modules.

    For example

    // VeryLongClass.ts
    
    class VeryLongClass {
      // ...
    }
    
    export default VeryLongClass;
    
    // runner.ts
    
    import { OtherClass } from 'other-class';
    import VeryLongClass from './VeryLongClass';
    
    OtherClass.run(VeryLongClass);
    

    This way it’s impossible to lose the run part and also helps in locating class files if they have one job only.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search