@types/node
In this page:
// npm install --save-dev @types/node
import * as fs from "fs";
const value: string | undefined = process.env.VARIABLE_NAME;
Installing Node.js Types
Installing @types/node adds type definitions for Node's built-in APIs — fs, path, process, and the rest — since Node's own runtime is plain JavaScript with no types of its own.
Example: Installing Node.js Types
// npm install --save-dev @types/node
console.log("@types/node provides types for fs, path, process, and more");
Using Built-in Modules
With @types/node installed, importing built-in modules like fs or path gives full autocomplete and type-checked function signatures instead of TypeScript treating each import as untyped.
Example: Using Built-in Modules
// import * as path from "path";
// const joined: string = path.join("a", "b");
console.log("With @types/node, path.join is fully typed and autocompleted");
Typing process
Typing process — its .env, .argv, and .exit() — comes from @types/node too, letting you catch a typo in an environment variable name or a wrong argument count for process.exit at compile time.
Example: Typing process
// process.env.NODE_ENV is typed as string | undefined
// process.exit(0) requires a number argument
console.log("process.env and process.exit are typed via @types/node");
NodeJS Types
The NodeJS namespace bundled in @types/node provides types for Node-specific concepts like NodeJS.Timeout (returned by setTimeout in Node, distinct from the browser's return type) and NodeJS.ProcessEnv.
Example: NodeJS Types
// let timeout: NodeJS.Timeout = setTimeout(() => {}, 1000);
console.log("NodeJS.Timeout differs from the browser's setTimeout return type");
Configuring Node Types
Configuring which Node types get loaded is done through the types array in tsconfig.json's compilerOptions, which matters when you want to limit ambient globals to just Node's, avoiding conflicts with browser DOM types in the same project.
Example: Configuring Node Types
// tsconfig.json: { "compilerOptions": { "types": ["node"] } }
console.log("The types array limits ambient globals to just Node's own");
- Forgetting
@types/node, so importingfsor usingprocessgives an error likeCannot find name process. - Installing
@types/nodeat a version that does not match your Node version, missing newer APIs. - Adding it to
dependenciesinstead ofdevDependencies, or expecting it to include runtime code.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: