kkost
kkost

Reputation: 3730

Typescript: undefined static variable issue

I can't understand why the next issue happens. Code with the same structure works fine in any other object-oriented languages like C# or Java. I am writing Node.Js app using Typescript.

So I have a class ServiceLocator with two static variables:

//ServiceLocator.ts
export class ServiceLocator {
    public static dataRepository: IDataRepository = new DataRepository();
    public static authService: IAuthService = new AuthService();
}

Class from the second one variable using the first one static variable. This how it looks:

//AuthService.ts
const dataRepository: IDataRepository = ServiceLocator.dataRepository;
export class AuthService implements IAuthService {
...
}

But once I am trying to get authService link like this:

//AuthController.ts
const authService: IAuthService = ServiceLocator.authService;
export class AuthController {

    public async signIn(request: Request, response: Response) {
        ..
    }
..
}

I got an error:

 TypeError: Cannot read property 'dataRepository' of undefined

What am I do wrong?

Upvotes: 4

Views: 3003

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159875

You have a circular reference here. In order to construct the AuthService module you need a fully constructed ServiceLocator class. However, JavaScript needs a fully constructed AuthService module in order to construct the ServiceLocator class. Switching the order of instantiation would simply result in an error from ServiceModule <cint> (to coin a Java-ism) along the lines of "Uncaught TypeError: undefined is not a constructor".

The solution is to simply make the dependency lazy:

//AuthService.ts
const dataRepositoryReference: IDataRepository = import('./ServiceLocator')
  .then(({ ServiceLocator }) => ServiceLocator.dataRepository);
export class AuthService implements IAuthService {
  public async findUserByUsername(username: UserName) {
    const dataRepository = await dataRepositoryReference;
    // ... snip ...
  }
}

Upvotes: 1

Related Questions