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.

TypescriptConfig Management

Code

typescriptsnippet
23 lines
// 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 /orders

Inside 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:http is 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

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.