0

I can't access an user private property of typescript class


import { Request, Response } from 'express'
import UserModel from '../models/UserModel'

class UserController {
  private User: UserModel[] = [
    {
      id: 1,
      name: 'Test 1',
      email: 'test1@test.com.br'
    },
    {
      id: 2,
      name: 'Test2 2',
      email: 'test2@test.com.br'
    }
  ]

  /**
   * [GET] /users
   * @param req: Request
   * @param res: Response
   */
  public async index (req: Request, res: Response): Promise <Response> {
    return res.json(this.User)
  }
}

export default new UserController()

When i access the route [GET] /users i've got the "TypeError: Cannot read property 'User' of undefined" error. I'm using async method because in a near future this route will be connected to database and now i'm testing the class with static users. How can i fix? Thanks

1 Answers1

2

Use an arrow function for the index method to ensure that this is bound to your instance of UserController:

public index = async (req: Request, res: Response): Promise <Response> => {
  return res.json(this.User)
}

Alternatively, you could use what you have already and bind the index method to the instance in the constructor:

class UserController {
  private User: UserModel[] = [
    {
      id: 1,
      name: 'Test 1',
      email: 'test1@test.com.br'
    },
    {
      id: 2,
      name: 'Test2 2',
      email: 'test2@test.com.br'
    }
  ]

  constructor() {
    this.index = this.index.bind(this)
  }

  /**
   * [GET] /users
   * @param req: Request
   * @param res: Response
   */
  public async index (req: Request, res: Response): Promise <Response> {
    return res.json(this.User)
  }
}
Steve Holgado
  • 11,508
  • 3
  • 24
  • 32