Module augmentation in TypeScript
Adding to another module's types from your own code.
import type { IncomingMessage } from "node:http";
declare module "node:http" {
interface IncomingMessage {
requestId?: string;
user?: { id: string; scopes: readonly string[] };
}
}
declare module "node:querystring" {
interface ParsedUrlQuery {
typestarTrace?: string;
}
}
export function tag(request: IncomingMessage, id: string): string {
request.requestId = id;
request.user = { id: "u-1", scopes: ["read"] as const };
return `${request.requestId}:${request.user.scopes.length}`;
}
console.log(typeof tag);
How it works
- Reopening the module merges your declarations into it.
- The file must be a module, or the declaration is global.
- This is how a plugin types the field it adds.
Keywords and builtins used here
IncomingMessageasconstdeclareexportfromfunctionimportinterfacereadonlyreturnstringtype
The run, in numbers
- Lines
- 22
- Characters to type
- 512
- Tokens
- 117
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 64 seconds.
Step 3 of 3 in Modules & declarations, step 7 of 8 in Async & modules.