Sub topic 3
Matching target and lib to your runtime
This chapter assumes you can read a basic tsconfig.json, know what tsc does, and have written TypeScript with interfaces and functions. It covers two options that decide which JavaScript your compiler emits and which built-in APIs it knows about: target and lib.
Two separate questions
The two options answer different questions.
targetcontrols syntax. It decides which language featurestscleaves alone and which it rewrites into older equivalents. Examples are arrow functions,classfields, optional chaining (?.), andasync/await.libcontrols type declarations. It decides which built-in names the type checker knows, such asPromise,Map,Array.prototype.at,Object.hasOwn, ordocument.
Neither option adds code at runtime. tsc does not polyfill missing APIs. If you use "abc".replaceAll("a", "b") and the runtime has no replaceAll, the program still crashes, even if the type checker accepted it.
A mismatch produces two common failure modes:
libis too old for your code. The compiler reportsProperty 'replaceAll' does not exist on type 'string'.libis newer than your runtime. The code type-checks and fails when it runs, because the function is missing.
How target works
target sets the ECMAScript version of the emitted JavaScript. Common values are ES2017, ES2020, ES2022, and ESNext. Syntax that the target supports is emitted unchanged. Syntax that it does not support is rewritten.
Take this source:
const user = { profile: { name: "Ada" } };
const name = user.profile?.name ?? "anonymous";
console.log(name);With "target": "ES2019", the compiler rewrites ?. and ?? into checks against null and undefined. With "target": "ES2020" or higher, it emits the original lines unchanged, because ES2020 introduced both operators.
Lowering syntax has a cost. The output is larger and sometimes slower. Some features, such as classes in very old targets, need helper code. For a Node.js service, a high target is almost always better.
Choosing a value
Pick the oldest runtime you must support, then use the highest target that runtime fully handles. Do not pick ESNext for code that ships to a fixed runtime. ESNext means "whatever the installed compiler considers latest", so upgrading TypeScript can change your output.
| Runtime | Reasonable target |
|---|---|
| Node.js 18 | `ES2022` |
| Node.js 20 and later | `ES2022` (a higher value is also fine) |
| Evergreen browsers (current Chrome, Firefox, Safari, Edge) | `ES2020` to `ES2022` |
| Older browsers, such as legacy mobile webviews | `ES2017` or lower, after checking your support matrix |
Treat the table as a starting point and check the runtime documentation for your exact versions.
Side effects of target
target also sets defaults for other options. The ones you will notice:
- It sets the default for
lib(see below). - At
ES2022and above,useDefineForClassFieldsdefaults totrue. Class fields then use standard define semantics instead of plain assignment. This changes behavior when a subclass redeclares a field, or when a field is declared without an initializer. - It affects the default for
module, in some TypeScript versions.
Because of these defaults, raising target can change runtime behavior even when no syntax is lowered differently.
How lib works
lib lists the groups of built-in type declarations the compiler loads. If you leave it out, the compiler picks a default based on target. For "target": "ES2022", the default includes the ES2022 library plus the DOM, which describes browser globals.
Naming lib explicitly replaces that default entirely. It does not add to it.
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"]
}
}This configuration describes a server environment. Because "DOM" is not listed, the compiler rejects document, window, and fetch typed from the DOM declarations. That is the point. A Node.js program has no document, and the compiler now reports the mistake.
Common lib entries:
| Entry | What it declares |
|---|---|
| `ES2022` (or another year) | Built-ins up to that edition, including all earlier editions |
| `ESNext` | The newest built-ins this compiler version knows |
| `DOM` | Browser globals such as `document`, `window`, and `HTMLElement` |
| `DOM.Iterable` | Iteration support for DOM collections such as `NodeList` |
| `WebWorker` | Globals available inside web workers |
| `ES2021.String` | A single feature group, for example `String.prototype.replaceAll` |
Year entries include earlier years, so ES2022 already contains ES2015 through ES2021. You only need one year entry.
Targeting a browser
A front-end project typically needs the DOM declarations:
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"]
}
}Adding one newer API
Suppose your target is ES2019, but your runtime and a polyfill provide Array.prototype.flat variants or replaceAll. You can add just the missing group instead of raising everything:
{
"compilerOptions": {
"target": "ES2019",
"lib": ["ES2019", "ES2021.String"]
}
}Only do this if the runtime really has the API. The type declaration is a promise from you to the compiler.
Node.js and platform types
lib covers the JavaScript language. It does not cover Node.js APIs such as fs, process, or Buffer. Those come from the @types/node package. Install it as a development dependency:
npm install --save-dev @types/nodeThe types option controls which @types/* packages load automatically. If you set "types": [], none do, and process becomes an unknown name. Leave types unset unless you have a reason to restrict it.
A related gotcha: fetch exists in Node.js 18 and later. Its type comes from @types/node in recent versions. Older versions of @types/node do not declare it, and you might add DOM to lib to get it. That also brings in window and document, which Node does not have. Prefer updating @types/node over adding DOM to a server project.
A worked mismatch
Here is code that uses a feature from ES2022:
const values = [10, 20, 30];
const last = values.at(-1);
console.log(last);Array.prototype.at arrived in ES2022. Compare three configurations:
"target": "ES2020"with nolib. The defaultlibis ES2020, so the compiler reportsProperty 'at' does not exist on type 'number[]'."target": "ES2020"with"lib": ["ES2022"]. The code compiles. Whether it runs depends on the runtime. Node.js 16.6 and later hasat, so this is safe if your minimum is Node 18."target": "ES2022". The code compiles, and the syntax is not lowered.
Case 2 shows that target and lib can differ on purpose. You might keep the target low for syntax compatibility with a bundler while the runtime supports newer built-ins. Keep the combination deliberate and documented.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Property 'x' does not exist on type ...` for a standard method | `lib` is older than the API | Raise `lib` or add the specific feature group |
| `Cannot find name 'document'` in browser code | `lib` set without `DOM` | Add `"DOM"` to `lib` |
| `Cannot find name 'process'` or `'Buffer'` | Missing Node types | Install `@types/node` |
| Code compiles but throws `x is not a function` at runtime | `lib` is newer than the runtime | Lower `lib`, or add a polyfill |
| `Promise` not found when `target` is very old | `lib` lacks ES2015 | Include at least `ES2015` in `lib` |
Checking the result
Run npx tsc --showConfig to see the resolved target and lib. Then run npx tsc --listFiles and look for entries like lib.es2022.d.ts and lib.dom.d.ts. These show exactly which declaration files the compiler loaded.
Exercise
A Node.js 18 service sets "target": "ES2022" and no lib. A developer adds document.title = "x" and the compiler accepts it. Explain why, and give the configuration change that makes the compiler reject it.
Show answer
With no lib, the compiler uses a default derived from target. For ES2022 that default includes the DOM declarations, so document is typed. Set "lib": ["ES2022"] explicitly. Because naming lib replaces the default, the DOM declarations are no longer loaded, and document becomes Cannot find name 'document'.
Exercise
Your code calls "a-b-c".replaceAll("-", "+"). The config is "target": "ES2019" with no lib, and the compiler reports an error. Name two ways to fix it, and state the risk of each.
Show answer
Option 1: raise target to ES2021 or higher, which raises the default lib. The risk is that the emitted syntax now assumes a newer runtime. Option 2: keep the target and add "lib": ["ES2019", "ES2021.String"]. The risk is that the runtime must really provide replaceAll, because tsc does not polyfill it. Either way, confirm the minimum runtime version supports replaceAll, which Node.js 15 and later does.