HTTP Module with Types
In this page:
Creating an HTTP Server
Creating an HTTP server with Node's built-in http module and @types/node gives the createServer callback correctly typed IncomingMessage and ServerResponse parameters instead of untyped raw objects.
Example: Creating an HTTP Server
// import * as http from "http";
// const server = http.createServer((req, res) => { res.end("ok"); });
console.log("createServer's callback receives typed IncomingMessage/ServerResponse");
Typing Incoming Requests
Typing incoming requests means using IncomingMessage's properties like .url and .method, both of which are typed as possibly undefined, correctly reflecting that a malformed raw HTTP request can omit them.
Example: Typing Incoming Requests
// (req: http.IncomingMessage) => {
// const url: string | undefined = req.url;
// const method: string | undefined = req.method;
// }
console.log("req.url and req.method are typed as possibly undefined");
Routing with Types
Routing with types typically means switching on req.method and req.url with narrowed string comparisons, since the built-in http module has no router of its own — any routing structure is something you type yourself.
Example: Routing with Types
function route(method: string, url: string): string {
if (method === "GET" && url === "/") return "home";
return "not found";
}
console.log(route("GET", "/"));
Typed JSON Responses
Sending a typed JSON response means calling res.end(JSON.stringify(data)) where data's shape is defined by an interface, so a typo in a response field name gets caught before it ever reaches a client.
Example: Typed JSON Responses
interface ApiResponse { status: string }
const data: ApiResponse = { status: "ok" };
// res.end(JSON.stringify(data));
console.log(JSON.stringify(data));
Typed Server Configuration
Typed server configuration — like the port number or TLS options passed to createServer/listen — catches basic mistakes like passing a string where a ListenOptions object or number is actually expected.
Example: Typed Server Configuration
interface ListenOptions { port: number; host?: string }
const options: ListenOptions = { port: 8080 };
// server.listen(options.port);
console.log("Listening on port", options.port);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: