Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type not being checked in custom response structure in Express

I am starting of with typescript and have hit a roadblock where I can’t figure out why types are not being validated.

Route

app.use((req: Request, res: Response) => {
  // here 404 is a string but should be a number according to type defined but no error is shown
  return res.error({ status: '404', message: 'The API route does not exist' })
})

Middleware

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface APIResponse {
  status: number,
  message?: string | null,
  data?: any
}

const responseHelper = (req: Request, res: Response, next: NextFunction) => {
  res.showDefaultErrorPage = (status: number = 500) => {
      //...
  }

  res.success = (options: APIResponse) => {
    const {
      status = 200,
      message = null,
      data
    } = options

    //...
  }

  res.error = (options: APIResponse) => {
    const {
      status = 500,
      message = null
    } = options

    //...
  }

  next()
}

export default responseHelper

Custom type definition for express response

/* eslint-disable no-unused-vars */
declare namespace Express {
  interface Response {
    showDefaultErrorPage?: any
    showErrorPage?: any
    success?: any
    error?: any
  }
}

>Solution :

You could change your type definiton to this:

declare namespace Express {
  interface Response {
    showDefaultErrorPage?: any
    showErrorPage?: any
    success?: (options: ApiResponse) => Response<any, Record<string, any>, number>
    error?: (options: ApiResponse) => Response<any, Record<string, any>, number>
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading