typescriptundefined

Why does typescript give "object is possibly undefined" when object is defined in constructor?


Title says it all. I don't see how this.authService could possibly be undefined after this.authService = new AuthService() in the constructor (or something incredibly close). The base class uses a base class of GenericApiService - why I have to use the const and pass to super before assignment.

export class AuthController extends CrudController<any> {
  authService: AuthService;

  constructor(app: Express) {
    const authService = new AuthService(database.db!);
    super('auth', app, authService);

    this.authService = authService;
  }

  registerUser(req: Request, res: Response, next: NextFunction) {
    // TS2532: Object is possibly undefined (definitely this line and definitely authService)
    this.authService.createUser(orgId, req.body)
      .then((doc) => {
        return res.status(201).json(doc);
      })
  }

Solution

  • After tearing the code down to the minimum amount to repro the problem, I found out the issue lied within the "createUser" method of authService, not the controller code I posted above. I thought I had a working function in createUser, but I had not declared a return type. It defaulted to a return type of

    Promise<never>
    

    which I'm not familiar with. After declaring a return type of

    Promise<User | void>
    

    the issue disappeared.

    If someone gets stumped by something similar in the future. Tear down the function you're calling and drastically simplify it - maybe you've got a bad return type.