简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM