Skip to content

TypeScript Setup

A proper TypeScript setup includes the compiler, a tsconfig.json file, and editor integration. This lesson walks through installing and running TypeScript in a real project.

TypeScript Setup Overview

Most projects install TypeScript as a dev dependency via npm or yarn. You initialize configuration with npx tsc --init, which creates tsconfig.json controlling target ECMAScript version, module system, and strictness.

Editor support from VS Code or WebStorm provides real-time type checking without running tsc manually. For production builds, integrate tsc or a bundler like esbuild, Vite, or webpack.

Step Command / File Purpose
Install npm install -D typescript Add compiler locally
Initialize npx tsc --init Create tsconfig.json
Compile npx tsc Emit JavaScript
Watch npx tsc --watch Recompile on save
Run node dist/index.js Execute output

TypeScript Setup Example

// package.json scripts
// "build": "tsc",
// "watch": "tsc --watch"

// tsconfig.json (excerpt)
// {
//   "compilerOptions": {
//     "target": "ES2020",
//     "module": "NodeNext",
//     "strict": true,
//     "outDir": "dist",
//     "rootDir": "src"
//   }
// }

A minimal setup separates source in src/ and compiled output in dist/. Enabling strict catches more errors. npm scripts make compilation repeatable for your whole team.

When to Use TypeScript Setup

Scenario Recommended Setup
Node.js backend tsc with module NodeNext and outDir
React with Vite Vite template with TypeScript
Library package tsc with declaration: true
Monorepo Project references in tsconfig
Existing JS project allowJs: true for gradual migration
Quick experiments TypeScript Playground or ts-node

Best Practices

  • Pin TypeScript version in package.json for reproducible builds
  • Commit tsconfig.json to version control
  • Use outDir to keep compiled JS separate from source
  • Enable strict mode from the start of new projects
  • Add a build script and run it in CI
  • Install @types/node for Node.js APIs
  • Exclude node_modules and dist from compilation

Common Mistakes to Avoid

  • Installing TypeScript globally but not in the project
  • Editing compiled JS instead of TS source files
  • Forgetting to set rootDir and outDir
  • Leaving noEmit false when using a bundler that handles TS
  • Not adding @types for untyped dependencies
  • Using incompatible module and target settings
  • Skipping .gitignore entries for dist/

Key Takeaways

  • Install TypeScript locally as a dev dependency
  • tsconfig.json controls compiler behavior
  • tsc compiles .ts files to .js
  • Watch mode speeds up development feedback
  • Editor integration complements command-line compilation
  • Match module settings to your runtime environment

Pro Tip

Run npx tsc --showConfig to see the effective configuration after extends and defaults merge. It saves hours when debugging mysterious compile errors.