25
loading...
This website collects cookies to deliver better user experience
Request
and Response
types, and haven't found anything that works without breaking something else or being complicated. So here's how I usually implement typesafety into express routes.import express from "express";
const app = express();
app.post("/user", (req, res) => {
req.body.name; // autocomplete doesn't work
});
app.listen(3000);
import express, {Request, Response} from "express";
...
app.post("/user", (req: Request, res: Response) => {
req.body.name; // autocomplete doesn't work
});
Request
and Response
type from the function automatically. So we didn't really do much here.req.body
autocomplete doesn't offer anything special. Let's change that.Request
type parameter list so that Typescript knows what variables are available in req.body
. It would look something like this:type UserRequestBody = { name: string };
app.post("/user", (req: Request<{}, {}, UserRequestBody>, res: Response) => {
req.body.name; // autocomplete works
});
{}
for the first two parameters as the thing we want (body) is actually the third type parameter. As we can see in the Request
definition:interface Request<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any, // this is the Request.body
...
type RequestBody<T> = Request<{}, {}, T>;
type RequestBody<T> = Request<{}, {}, T>;
type UserRequestBody = { name: string };
app.post("/user", (req: RequestBody<UserRequestBody>, res: Response) => {
req.body.name; // autocomplete works
});
// for .body
type RequestBody<T> = Request<{}, {}, T>;
// for .params
type RequestParams<T> = Request<T>;
// for .query
type RequestQuery<T> = Request<{}, {}, {}, T>;
// and so on... similarly for Response
.body
and .params
. We can do so by simply adding a new type:type RequestBodyParams<TBody, TParams> = Request<TParams, {}, TBody>
import express, {Request, Resposne} from "express";
const app = express();
type RequestBody<T> = Request<{}, {}, T>;
type UserRequestBody = { name: string };
app.post("/user", (req: RequestBody<UserRequestBody>, res: Response) => {
req.body.name; // autocomplete works
});
app.listen(3000);