Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 96 ยท TypeScript in Practice

Monorepos and Shared Types

Share TypeScript types between apps in one repository with npm workspaces, shared packages, project references, path mapping, exports and how to keep builds fast and types consistent.

Sooner or later a project grows a second app. There's a web front end and an API, or a mobile app and a worker, and they both need to agree on what a User or an Order looks like. Copying interfaces between repositories guarantees they drift apart. A monorepo keeps several packages in one repository, so they can import each other, share one set of types and be changed together in a single commit.

This lesson shows how TypeScript monorepos are put together: package manager workspaces, a shared types package, a base tsconfig, project references, and path mapping. The file layouts are read-only (our runner has one file and no package manager), and the runnable examples simulate the two ideas that matter most: how a workspace name is resolved, and how a shared contract keeps two apps consistent.

The shape of a monorepo

A typical layout puts deployable apps and reusable libraries side by side:

TEXT
my-company/
  package.json            <- declares the workspaces
  tsconfig.base.json      <- compiler options shared by everyone
  apps/
    web/                  <- front end
      package.json
      tsconfig.json
      src/
    api/                  <- back end
      package.json
      tsconfig.json
      src/
  packages/
    contracts/            <- shared types and schemas
      package.json
      tsconfig.json
      src/
    utils/                <- shared helpers
      package.json
      tsconfig.json
      src/
flowchart TD
  web["apps/web"] --> contracts["packages/contracts"]
  api["apps/api"] --> contracts
  api --> utils["packages/utils"]
  web --> utils
  contracts --> utils

Apps depend on shared packages; packages never depend on apps. Keep the arrows pointing one way.

The rule in the diagram matters: dependencies flow from apps down to libraries. A library that imports from an app creates a cycle and makes the shared code impossible to reuse.

Package managers (npm, pnpm, Yarn, Bun) support workspaces. The root package.json lists where packages live:

JSON
{
  "name": "my-company",
  "private": true,
  "workspaces": ["apps/*", "packages/*"]
}

When you run npm install, the package manager finds every package.json below those folders and links the packages into node_modules. Each package has a name, and other packages depend on it by that name:

JSON
{
  "name": "@acme/contracts",
  "version": "0.0.0",
  "private": true,
  "type": "module",
  "exports": {
    ".": "./src/index.ts"
  }
}
JSON
{
  "name": "@acme/api",
  "private": true,
  "dependencies": {
    "@acme/contracts": "*"
  }
}

(pnpm and Yarn spell the local dependency workspace:*, which means "only ever use the copy in this repository".) After installing, import type { User } from '@acme/contracts' inside apps/api resolves to the real folder through a symlink. No publishing to npm is needed.

The exports field decides what other packages may import. Pointing it at ./src/index.ts is the "internal package" style: the consuming app's bundler or runtime compiles the TypeScript itself, which is simple and fast during development. If you publish a package or have consumers that can't compile TypeScript, build to JavaScript and point exports at the dist folder, with a types entry for the .d.ts files (see Declaration Files).

One base tsconfig, many small ones

Compiler options belong in one place. Put them in a base file:

JSON
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "nodenext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "skipLibCheck": true,
    "declaration": true,
    "composite": true
  }
}

and extend it in each package:

JSON
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": { "outDir": "dist", "rootDir": "src" },
  "include": ["src"],
  "references": [{ "path": "../../packages/contracts" }]
}

extends copies options; it does not link packages. Read tsconfig.json if any of these options are unfamiliar. Strictness should be identical everywhere, otherwise shared code is checked by one rule in one app and a looser rule in another.

Project references

The composite option and references array turn each package into a separate project. Running tsc --build (or tsc -b) then does three useful things:

  • It builds projects in dependency order, so contracts is ready before api needs its .d.ts files.
  • It remembers what is up to date and skips projects whose inputs haven't changed.
  • It lets editors check each package on its own instead of loading the whole repository as one giant program.
Terminal
tsc --build           # build everything that is out of date
tsc --build --watch   # rebuild as files change
tsc --build --clean   # remove build outputs

Large codebases (see Large Projects) lean on this for fast CI. The root tsconfig.json is often just a list of references with "files": [], so a single tsc -b at the root checks the whole repository.

Path mapping, and when not to use it

TypeScript's paths option rewrites import specifiers:

JSON
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@acme/contracts": ["packages/contracts/src/index.ts"],
      "@acme/utils/*": ["packages/utils/src/*"]
    }
  }
}

This is the one that surprises people: paths only affects type checking. It doesn't change the emitted JavaScript, so at runtime Node or your bundler still sees @acme/contracts and needs another way to find it. With workspaces that other way already exists (the node_modules link), so you often don't need paths at all. Use it for:

  • shortcuts inside one app, like @/components/Button (your bundler needs the same alias),
  • pointing editors at source files instead of built .d.ts files during development.

Treat the mapping and the runtime resolution as two things that must agree. The first TryIt below simulates how a name becomes a file, so you can see why.

TypeScript Resolving workspace names and path aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first match wins, and an unknown name falls through to node_modules. If tsc resolves an import through paths but your bundler has no matching alias, you get a program that type-checks and then fails at runtime with "module not found".

What belongs in a shared package

Share what both sides must agree on, and nothing more:

  • Contracts: request and response types, enums of statuses, event payloads. If you use schemas (Validating Data with Zod), share the schema and export its inferred type, so the API validates and the front end gets the same type.
  • Pure helpers: formatting, date math, ID parsing that has no dependency on Node or the DOM.
  • Config presets: shared tsconfig bases and lint rules.

Keep shared packages free of runtime assumptions. A utils package that imports node:fs can't be used from the browser, and one that touches window can't run on the server. When the code has environment-specific parts, split the package or use conditional exports.

The second TryIt shows the payoff of a shared contract. Both "apps" import the same definitions, so a rename or new field is a compile error everywhere at once.

TypeScript One shared contract, two consumers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
#1 [$] paid $49.99
#2 [ ] pending $12.50
#3 [>] shipped $200.00

Add a 'cancelled' status to the contract and badge stops compiling until the front end handles it, because a Record<OrderStatus, string> must have every key. That's the monorepo promise: a change to the contract surfaces everywhere it matters, before anything is deployed. (In a real repository the three sections would be separate packages.)

Practical tips

  • Type-check from the root. Add a root script such as "typecheck": "tsc --build" and run it in CI; per-package scripts alone can miss cross-package breakage.
  • Use a task runner for scale. Tools like Turborepo or Nx cache build and test results per package and run only what changed. They're optional for small repositories.
  • Pin tool versions once. Keep typescript as a root dev dependency so every package uses the same compiler.
  • Avoid deep imports. Import from the package entry (@acme/contracts), not @acme/contracts/src/internal/thing. The exports field enforces this.
  • Use import type for types from other packages, so a type-only dependency never becomes a runtime one (see Modules).
  • Watch for circular dependencies. If two packages need each other, extract the shared part into a third.

tsc --build needs composite: true (which implies declaration) in every referenced project. If you see "Referenced project must have setting composite: true", that's the cause.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do package manager workspaces do?

    Workspaces make the package manager find every package.json under the listed folders and link them into node_modules, so one package can depend on another by its name without publishing.
  2. 2. What does the "extends" option in a package's tsconfig.json do?

    extends only inherits compiler options. Linking packages is done by workspaces (for resolution) and by "references" (for build order and incremental builds).
  3. 3. Why can a project that uses paths type-check fine but fail at runtime?

    The compiler uses paths to find types, but the JavaScript keeps the original specifier. The bundler or runtime needs its own matching alias or workspace link.
  4. 4. What does tsc --build give you over plain tsc?

    With composite projects and references, tsc --build orders the work and reuses outputs for projects whose inputs have not changed.
  5. 5. Which is a good candidate for a shared package?

    Contracts are what both sides must agree on. Environment-specific code and anything that depends on an app should stay out of shared libraries.

Summary

  • A monorepo keeps apps and shared packages in one repository so types and changes stay in sync.
  • Workspaces link packages by name through node_modules; exports controls what a package exposes.
  • Share one tsconfig.base.json with extends, but note that extends copies options and links nothing.
  • Project references with composite and tsc --build give ordered, incremental builds across packages.
  • paths is a type-checking aid only; make sure your bundler or runtime resolves the same names.
  • Share contracts (types, schemas, enums) and pure helpers; keep dependencies flowing from apps to libraries, never in circles.

Next: Testing Types