Home > Net >  Type not being checked in custom response structure in Express
Type not being checked in custom response structure in Express

Time:08-28

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

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
  }
}

CodePudding user response:

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>
  }
}
  • Related