TypeScript configuration
This one is going to be a complicated one, but I need to write this down while I still remember how this actually works.
Let me start with a brief context. We all use TS configuration (yeah, tsconfig.json) but we often just copy-paste it
from other projects and touch it whenever something needs fixing. An even smaller number of people actually understand
what's going on there. I'm going to try to explain it here.
With TypeScript configuration, you can specify things like:
- what files should be processed by TS.
- what environment you're targeting (node or browser) and ES version.
- what kind of module system you're using (commonjs, esm, ...).
- monorepo configuration using project references.
- how strict the compiler should be.
- and many more things...
As you can imagine, things can get complicated pretty quickly, and doing some things properly is pretty hard. For example:
- Publishing a package with multiple targets and configuring the
exportsfield properly. There are probably a handful of people who actually understand how this works. Read ESM modernization lessons to understand the pain of even upgrading to ESM. Similarly, read the ESM package notes. - The bridge between server and browser is collapsing. Take React server components. Or even plain Next.js. You have a
single project, but part of the code runs on the server (
pages/api) and part on both...
Anyway, let's get to the meat.
How many TS configs should I have?
Depends on the project.
TS configs for libraries
By library, I mean a package that needs to be published. Ideally, you want to have the following:
- Ship only the production files (exclude tests) in JS (so that JS people can use the package as well).
- TS typings
The best way to do the following is to have two separate TS configs. Have one to lint all the files, and another one that you use for building the package.
The idea is simple. Have a "main" TS config that includes all project files. This is nice because other tools look for
tsconfig.json in the root and use that for linting the project (for example, your IDE). Then, have a separate "build"
config which extends the "main" one. When building the package, use the "build" config.
For example (note, that I've removed all configuration irrelevant to publishing):
// tsconfig.json
{
"compilerOptions": {
"noEmit": true // This config file is used for linting and not for compilation. It should not emit any files during compilation.
},
"exclude": ["dist/**/*", "coverage/**/*", "node_modules/**/*"], // This is project specific.
"include": [
"**/*", // Include all ".ts", ".tsx", and ".d.ts" files. If "allowJs" is enabled, also ".js" and ".jsx" ones.
// Files/folders starting with "." are ignored by glob patterns and need to be included explicitly. See:
// https://github.com/microsoft/TypeScript/issues/13399#issuecomment-271939777
".eslintrc.js"
]
}
// tsconfig.build.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false, // We want to create the compiled (transpiled) files.
"outDir": "dist", // In the dist directory.
"declaration": true, // Generate separate ".d.ts" files for TypeScript typings.
"declarationMap": true, // Create source maps for the typings, so when you do "Go to Definition" in the IDE (for a type), you're navigated to the source TypeScript file.
"sourceMap": true // Generate source maps, so when you do "Go to Definition" in the IDE (for a value), you're navigated to the source TypeScript file.
},
"include": ["./src/**/*"],
"exclude": ["./src/**/*.test.ts"]
}
// package.json
{
"files": [
"dist",
"src" // The source maps point to the actual source code, so we bundle that for production as well.
],
"scripts": {
"build": "tsc --project tsconfig.build.json",
"tsc": "tsc --project ." // By default, it looks for tsconfig.json (but you can be explicit if you want).
}
// Here, you should have at least the "main" and "exports" fields. See: https://nodejs.org/api/packages.html#package-entry-points.
}
Side note, I really hate when I see the shorthands in package.json scripts (and in other places as well). Reading the
code is much more important than saving a few characters. Please, I beg you, stop doing this.
TS configs for applications
Just maintain a single TS config in the root of the project, unless there's a need for more.
When to have multiple TS configs?
Applications can be complex, and there are cases where you might need multiple TS configs. Examples include:
- Conflicting types. For instance,
jestandcypressdon't play well together, and they argue overitand other test functions. - Different strictness requirements. I prefer enabling exactOptionalPropertyTypes and noUncheckedIndexedAccess for production code, but they might be overkill for tests.
Despite these scenarios, I still recommend extending the "main" TS config and only overriding the settings you need to. For instance:
{
"compilerOptions": {
"noUncheckedIndexedAccess": false,
"types": ["cypress", "node", "@testing-library/cypress"]
}
}
Strictness
New projects should use the strictest configuration possible, even to the point of pedantic strictness. Migrating existing projects might be challenging, so you can consider relaxing the configuration. Tests and scripts used only for build/dev can also have a more relaxed setup.
While it may not come as a surprise, TypeScript continually updates and introduces new checks. For a comprehensive list of available options, refer to the docs.
{
"compilerOptions": {
// ** Disabled rules. **
"allowUnusedLabels": true, // Prefer allowing variables starting with "_", ESLint should handle this.
"noUnusedLocals": false, // Handled by ESLint.
"noUnusedParameters": false, // Handled by ESLint.
"useUnknownInCatchVariables": false, // Disliked due to catch syntax and seldom use of non-Error throws.
// ** Enabled rules. **
"allowUnreachableCode": false, // If needed, use "ts-expect-error" comment.
"strict": true, // Enables a set of strictness rules.
"exactOptionalPropertyTypes": true, // Distinguish between absence and undefined.
"noFallthroughCasesInSwitch": true, // Prevent potential bugs in switch cases.
"noImplicitOverride": true, // Sensible rule for class structures.
"noImplicitReturns": true, // Usually indicates a bug.
"noPropertyAccessFromIndexSignature": true, // Despite awkwardness with "process.env", it's beneficial.
"noUncheckedIndexedAccess": true, // Good for new projects; use `!` if required.
// ** Rules implicitly enabled by "strict" mode. **
"alwaysStrict": true,
"noImplicitAny": true, // Might be disabled in legacy projects.
"noImplicitThis": true,
"strictBindCallApply": true,
"strictFunctionTypes": true,
"strictNullChecks": true, // Use `!` if required.
"strictPropertyInitialization": true,
"useUnknownInCatchVariables": true
}
}
Important thing to mention. If you have a strict config, TS will complain a lot (especially with
noUncheckedIndexedAccess), but do not be afraid to use ! and casting to silence the errors. Often TS does not have
enough context (e.g. something was already checked elsewhere) but there is a big distinction between consciously
"helping" the inference and not being aware of potential issues.
Monorepo configuration (project references)
With TS and monorepos, you face these issues:
- You likely want to have a TS config per package but also want to lint all packages together for testing.
- When you use a monorepo package in another and use the IDE feature
Go to Definition, you are navigated tonode_modules. - Linting & building speed.
With project references, you can address the problems above. However, the configuration isn't straightforward.
TypeScript will also create .tsbuildinfo files to facilitate this. These files should never become outdated, but if
they do, troubleshooting becomes challenging. The configuration setup can be complicated, but it's likely still
beneficial for intricate projects.
Read about project references in the TS docs, and you can view an implementation in API3 Airnode.
Config inheritance
TS config inheritance is pretty complex. Some fields are inherited and some are not. Some are overwritten and some are merged. It's hard to reason about this.
Also, it might not be clear what happens when there is a TS config that inherits the include and exclude from
another TS config. Thankfully, this works fine and they are resolved relative to the config file (so in this case, they
would be resolved relative to the parent TS config). Note, if the parent TS config defines both include and exclude
and the child TS config only include, then the exclude from the parent TS config is used (as expected).
As a rule of thumb, all fields are inherited with the exception of composite, which has its own reasoning and is
explicitly warned about when using project references. The
compilerOptions are merged shallowly.
The files, include and exclude settings
Read https://www.typescriptlang.org/tsconfig#files.
The important parts that are not obvious:
- You don't want to use
files. Useincludeandexclude. excludeonly excludes files that are included by one of the patterns mentioned ininclude. This is written in the docs as Important, but I always forget this.includedoes not include hidden files (starting with.). You need to include them explicitly. Such as.eslintrc.js. This doesn't matter much, but when using TS rules in ESLint, the config complains about not being listed in any TS config.- Both
includeandexcludecan be inherited via config extension, but it's better to be explicit and define both properties (and often you want to change them anyway in the child config). - Some patterns to know:
**/= Treated as any (nested) directory. Matches ".ts", ".tsx", and ".d.ts" by default, with ".js" and ".jsx" ifallowJsis set to true.**/*,./**/*= Both are the same as above.
The target setting
Read https://www.typescriptlang.org/tsconfig#target.
Set target to ES6 for FE apps as all modern browsers support that. For Node.js, the target depends on the minimal
Node.js version you're targeting. For Node@^16 you
can use target
es2021. See the community maintained configurations for other Node
versions.
The module and moduleResolution settings
Read https://www.typescriptlang.org/tsconfig#module.
Set module to nodenext if your app is running on Node.js. Otherwise, set it to esnext. You should use a bundler to
bundle your FE code and they should understand the esnext output of TS. If there are some issues, fallback to ES6
which they should understand since the spec was finalized in June 2015 (a.k.a at the time of dinosaurs).
The moduleResolution field was renamed from node to node10 and node16 and nodenext were added.
The esModuleInterop setting
Read https://www.typescriptlang.org/tsconfig#esModuleInterop.
Set module to node16 and let TS pick the right value for you.
The lib setting
Read https://www.typescriptlang.org/tsconfig#lib.
Set correct target and let TS pick the lib values for you. Specify the field only when you need to (e.g. need to use
"WebWorker" because that is not included by any target).
The documentation doesn't mention how exactly does TS derive the lib value. My friend chat GPT told me:
- If
targetis:"ES3"- The default libs included are["DOM", "ES3"]."ES5"- The default libs included are["DOM", "ES5", "ScriptHost"]."ES6"or"ES2015","ES2016"or any higher version - TypeScript includes the library file corresponding to that version, along with prior versions' features up to"ES5". For example, if you specify"ES2018", the default included libs will effectively represent the combined features of"DOM","ES5","ScriptHost","ES2015","ES2016","ES2017","ES2018", although there isn't a direct one-to-one mapping for each.
The skipLibCheck and skipDefaultLibCheck settings
Read https://www.typescriptlang.org/tsconfig#skipLibCheck.
Set skipLibCheck to true. It will speed up compilation time and you can't do anything with broken configurations of
dependencies anyway.
The baseUrl and paths settings
Read https://www.typescriptlang.org/tsconfig#baseUrl and https://www.typescriptlang.org/tsconfig#paths.
Do not use baseUrl. It is only relevant for AMD (which no-one really uses). And do not use paths either.
The idea behind these is to support import aliases to avoid relative imports hell (e.g. ../../../../../a/b/c/d). This is nice for very large projects, but I have a big disgust against this. First of all, you need to configure all other tools to understand your aliases which can be sometimes impossible. Furthermore, your IDE should be perfectly fine auto-importing the correct files. The big advantage comes during refactors when moving files. Still, I don't think it's worth it.
The types and typeRoots settings
Read https://www.typescriptlang.org/tsconfig#types and https://www.typescriptlang.org/tsconfig#typeRoots.
Do not use typeRoots unless you know what you are doing. Use types when there are
multiple conflicting typings and you want choose the correct one.
Conclusion
TypeScript is great and it's a hill I am willing to die on. Moreover, compared to strict typing systems like C++ or Java we can enjoy the benefit of running the code even without all errors being fixed. This is really, really great. Configuring TypeScript is a complex task, because there is so much to choose and the compiler needs to do so much. I hope this made at least some sense to you and thanks for sticking to the end.
One thing that drives me a bit crazy is that I often see TS configuration with values being lowercase or capitalized. TS config indeed ignores the case so you can use any.
Follow TS updates about what is new and what is coming. Subscribe to their official announcements channel.