TypeScript Best Practices

Chapter 1 · Practice 3 of 6

Set types and rootDir explicitly

From Compiler settings and TypeScript 7

Why it matters

TypeScript 6.0 changed two defaults that surprise people on upgrade, and TypeScript 7.0 keeps them:

  • types now defaults to []. Global type packages under @types, such as @types/node or a test runner's globals, are no longer included automatically. List the ones you need, for example "types": ["node"]. Setting ["*"] restores the old behavior, but an explicit list is clearer and faster.
  • rootDir now defaults to the directory that contains tsconfig.json. If your source lives in src/ and you emit to dist/, set rootDir to ./src or your output folder will gain an extra src/ level.

Being explicit about both also stops a stray @types package, pulled in by some dependency, from adding globals your code should not see.

Do

  • List global type packages in types, such as ["node"] or ["node", "vitest/globals"]
  • Set rootDir and outDir together when you emit JavaScript

Avoid

  • Relying on every @types package in node_modules being picked up automatically

Example

JSON
{
  "compilerOptions": {
    "types": ["node"],
    "rootDir": "./src",
    "outDir": "./dist"
  },
  "include": ["src"]
}