Type Only Imports With import type
Mark type-only imports with import type so transpilers erase them and runtime bundles never pull modules used solely for annotations.
Code
// import type:只引用类型,转译后整行被擦除
import type { IncomingMessage } from 'node:http';
interface RouteContext {
method: string;
path: string;
}
function toContext(req: IncomingMessage): RouteContext {
return { method: req.method ?? 'GET', path: req.url ?? '/' };
}
const fake = { method: 'POST', url: '/orders' } as unknown as IncomingMessage;
console.log('context:', toContext(fake).method, toContext(fake).path);
type RouteHandler = (ctx: RouteContext) => Promise<void>;
const handler: RouteHandler = (ctx) => {
console.log('handling', ctx.method, ctx.path);
return Promise.resolve();
};
handler(toContext(fake));Output
Captured from a sandboxed run of this snippet in the build pipeline.
context: POST /orders
handling POST /ordersInside the code
The code’s whole job belongs to the function toContext.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Returns a newly built value, leaving the inputs as they were.
What to watch for
node:httpis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Applying it
The signature that matters reads function toContext(req: IncomingMessage)
The demo output is labeled (context:, handling), so the printed lines read as a per-operation trace of the run.
Statements that matter
return { method: req.method ?? 'GET', path: req.url ?? '/' };
type RouteHandler = (ctx: RouteContext) => Promise<void>;
return Promise.resolve();
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does `toContext` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- What does this import from outside the project?
- Only `node:http`, and that is a Node.js built-in — it comes with the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.