#Override express res.json type to only accept specific type

2 messages · Page 1 of 1 (latest)

proud light
#

Anyone know how I can make Express' express.Response.json method only accept objects with my DataOrError type?

type DataOrError = {error: any; data?: never} | {error?: never; data: any}

app.use((error: any, req: Request, res: Response, next: NextFunction) => {
    res.status(500).json({ error: error })    // <= I only want the .json to accept objects with type `DataOrError`
})
silent hinge
#

You can extends Response and override json() method ?

type DataOrError = {error: any; data?: never} | {error?: never; data: any}
interface DataOrErrorResponse extends Response {
    json: (body: DataOrError) => this
}

app.use((error: any, req: Request, res: DataOrErrorResponse, next: NextFunction) => {
    const toto: DataOrError = {error: error}
    res.status(500).json(toto)    // <= I only want the .json to accept objects with type `DataOrError`
})

This is compiling OK. I let you test if it's behaving OK