Sub topic 3
Matching `target` and `lib` to Your Runtime
Prerequisites
Assume you know basic TypeScript configuration and can run npx tsc from a Node.js project. You should also know that a JavaScript runtime is the environment that executes your compiled code, such as Node.js, a browser, or a serverless platform.
Two compiler options answer different questions:
| Option | Question it answers | Main effect |
|---|---|---|
| `target` | Which JavaScript syntax can the runtime execute? | Controls syntax emitted by TypeScript |
| `lib` | Which built-in APIs should TypeScript describe? | Controls available type declarations |
Choosing `target`
The target option tells TypeScript how modern the emitted JavaScript may be. For example, target: "ES2022" allows modern syntax, while target: "ES2019" asks TypeScript to transform more syntax for older runtimes.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"outDir": "dist",
"strict": true
},
"include": ["src"]
}If your application runs on a recent Node.js version, a recent ECMAScript target usually produces simpler output. If it runs in older browsers, choose a target supported by those browsers or use a build tool that performs additional transformations.
target does not add missing runtime features. TypeScript may transform syntax, but it does not automatically provide a Promise, Map, or other API that the runtime lacks. You need a polyfill, a compatible runtime, or a different implementation for missing APIs.
Choosing `lib`
The lib option selects TypeScript's declaration files for built-in JavaScript and platform APIs. A declaration file contains types, not executable code.
For a Node.js application using modern JavaScript APIs, you might use:
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "NodeNext",
"strict": true
}
}For browser code, include the DOM declarations:
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"strict": true
}
}With DOM, TypeScript understands names such as document, Window, and HTMLElement. Do not add DOM to server code merely to silence an error. That can make TypeScript accept browser APIs that will fail at runtime.
If you omit lib, TypeScript chooses a default library based largely on target. Set it explicitly when the runtime and platform need to be clear, especially in shared packages.
A practical matching process
Use this sequence:
- Identify every runtime that executes the output.
- Choose the oldest syntax level those runtimes support.
- Select libraries for the APIs that truly exist there.
- Test the emitted code in the real runtime.
- Add polyfills separately when an API is missing.
Exercise
Why can lib: ["DOM"] make a Node.js project appear correct when it is not?
Show answer
It adds browser API types such as document, so TypeScript may accept code that Node.js cannot execute. The declaration does not provide the browser API at runtime.