Explorer
Typescript

TypeScript Setup & tsconfig.json Configuration Guide

Learn how to set up TypeScript, configure its compiler, and create a reliable development workflow.

Imagine joining a development team where everyone uses a different TypeScript version.

Your code works locally, but another developer gets type errors. The build server behaves differently, and nobody knows which configuration is correct.

How do we make TypeScript behave consistently across an entire project?

That's where project-level dependencies and tsconfig.json come in.

In this chapter, we'll set up a TypeScript project from scratch, understand its essential configuration options, and compile our first application.

1. Why Does TypeScript Need Configuration?

JavaScript can run directly in Node.js, but TypeScript projects typically use a compiler or build tool to check types and prepare executable code.

The compiler needs to know:

  • Which files belong to the project?

  • Which JavaScript version should be generated?

  • How strictly should types be checked?

  • Where should the compiled files be stored?

  • How should imports and modules be handled?

These decisions are defined through tsconfig.json, TypeScript's project configuration file.

Before creating it, we need to install TypeScript.

2. Setting Up a TypeScript Project

Step 1: Initialize the project

Make sure Node.js and npm are installed.

JAVASCRIPT
node --version
npm --version

Create a new project:

JAVASCRIPT
mkdir typescript-app
cd typescript-app
npm init -y

This generates a package.json file to manage dependencies and project scripts.

Step 2: Install TypeScript

There are two common installation methods.

Global installation

JAVASCRIPT
npm install -g typescript

Makes the TypeScript compiler available across projects in your current npm environment.

Local installation — Recommended

JAVASCRIPT
npm install -D typescript

Installs TypeScript as a development dependency within the project.

Global installation

Local installation

Shared compiler installation

Project-specific dependency

May cause version mismatches

Records the project's version requirement

Useful for experiments

Preferred for team projects

Local installation alone doesn't guarantee identical versions. For reproducible builds, commit package-lock.json and use npm ci in CI/CD.

Step 3: Install type definitions

When working with Node.js, TypeScript needs declarations describing its APIs.

JAVASCRIPT
npm install -D @types/node

This allows TypeScript to understand APIs such as:

JAVASCRIPT
import { readFileSync } from "node:fs";

const content = readFileSync("data.txt", "utf8");

What is @types/node?

It provides TypeScript type declarations for Node.js APIs. These declarations support autocomplete and type checking without adding runtime JavaScript.

Other libraries may provide separate @types packages, although many modern libraries include their own declarations.

Step 4: Initialize TypeScript

JAVASCRIPT
npx tsc --init

This creates tsconfig.json.

The generated configuration varies by TypeScript version. We'll replace it with a minimal setup that is easier to understand.

3. Understanding tsconfig.json

Think of tsconfig.json as the rulebook for the TypeScript compiler.

It controls type checking, file selection, module handling, and JavaScript output.

Let's create a simple configuration for a Node.js application using CommonJS.

JAVASCRIPT
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "moduleResolution": "Node10",
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "noEmitOnError": true,
    "sourceMap": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

3.1 Essential compiler options

Option

Purpose

target

JavaScript version to generate

module

Module format and associated compiler behavior

moduleResolution

How imported modules are resolved

rootDir

Source root used to organize emitted files

outDir

Destination for compiled output

strict

Enables stricter type checking

noEmitOnError

Prevents output when errors are reported

sourceMap

Generates source maps for debugging

include

Selects initial source files using patterns

exclude

Excludes files from include discovery

Let's understand the options that matter most.

3.2 rootDir vs outDir

Consider the following source structure:

JAVASCRIPT
src/
├── index.ts
└── utils/
    └── math.ts

With this configuration:

JAVASCRIPT
{
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./dist"
  }
}

The compiler preserves the relative directory structure:

JAVASCRIPT
dist/
├── index.js
└── utils/
    └── math.js
  • rootDir determines the source root used for emitted file paths.

  • outDir determines where compiled files are written.

An important distinction: rootDir does not decide which files TypeScript compiles. The include, exclude, and files options define the initial source-file selection.

3.3 target — JavaScript output version

JAVASCRIPT
{
  "compilerOptions": {
    "target": "ES2020"
  }
}

target tells TypeScript which JavaScript language version to generate.

For example, a modern target can preserve arrow functions, while an older target may transform them into traditional functions.

Common targets include ES2017, ES2020, ES2022, and ESNext.

Choose a target compatible with your supported runtime environments.

3.4 strict — Catch mistakes earlier

JAVASCRIPT
{
  "compilerOptions": {
    "strict": true
  }
}

Strict mode enables several additional type-checking rules.

For example:

JAVASCRIPT
function greet(name) {
  return `Hello ${name}`;
}

With strict checking, TypeScript reports an error because name implicitly has the any type.

Correct version:

JAVASCRIPT
function greet(name: string): string {
  return `Hello ${name}`;
}

For new projects, enabling strict: true is a sensible default.

3.5 include and exclude

JAVASCRIPT
{
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

include selects matching source files.

exclude removes matching files from that initial selection, although imported dependencies may still become part of the program.

For this project, TypeScript discovers .ts files in src and its subdirectories.

4. Compile and Run Your First TypeScript Application

Now let's use the configuration in a working project.

Step 1: Create the source file

Create src/index.ts:

JAVASCRIPT
function greet(name: string): string {
  return `Hello, ${name}`;
}

console.log(greet("Rahul"));

Step 2: Add npm scripts

Inside package.json, add:

JAVASCRIPT
{
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "typecheck": "tsc --noEmit"
  }
}

These scripts define three responsibilities:

  • build compiles TypeScript into JavaScript.

  • start executes the compiled JavaScript.

  • typecheck checks types without generating output.

Step 3: Build the application

JAVASCRIPT
npm run build

TypeScript generates dist/index.js:

JAVASCRIPT
"use strict";

function greet(name) {
  return `Hello, ${name}`;
}

console.log(greet("Rahul"));

Notice that the string annotations have disappeared.

Step 4: Execute JavaScript

JAVASCRIPT
npm start

Output:

JAVASCRIPT
Hello, Rahul

Final project structure

JAVASCRIPT
typescript-app/
│
├── src/
│   └── index.ts
│
├── dist/
│   ├── index.js
│   └── index.js.map
│
├── package.json
├── package-lock.json
└── tsconfig.json

The .js.map file is generated because we enabled sourceMap.

You now have a working TypeScript application with separate source files and compiled output.

5. Development Tools and Production Practices

Running the compiler and restarting Node.js after every change can become repetitive.

Modern tools can simplify development, but it's important to understand what they actually do.

5.1 Using tsx during development

Install tsx:

JAVASCRIPT
npm install -D tsx

Add a development script:

JAVASCRIPT
{
  "scripts": {
    "dev": "tsx watch src/index.ts"
  }
}

Run:

JAVASCRIPT
npm run dev

tsx transforms and executes TypeScript while watching for changes.

However, it does not replace complete TypeScript type checking.

For that, run:

JAVASCRIPT
npm run typecheck

5.2 CommonJS vs ES Modules

Node.js supports two major module systems.

CommonJS

JAVASCRIPT
const fs = require("node:fs");

ES Modules

JAVASCRIPT
import { readFileSync } from "node:fs";

The module and moduleResolution settings determine how TypeScript handles modules.

Our example uses CommonJS for simplicity.

For modern native Node.js ESM applications, NodeNext settings are often appropriate, along with the correct package.json configuration.

Frameworks such as Next.js and Vite use their own recommended module and build configurations.

Avoid copying a tsconfig.json configuration between unrelated frameworks without checking their requirements.

5.3 Production practices worth remembering

  1. Use local dependencies: Keep TypeScript in project-level devDependencies.

  2. Enable strict checking: Prefer strict: true for new projects.

  3. Run type checking in CI: Use tsc --noEmit when another tool handles bundling.

  4. Prevent unsafe builds: Use noEmitOnError when appropriate and ensure deployment fails if type checking fails.

These practices help make builds more predictable and reduce avoidable type-related problems.

6. Common Mistakes

Mistake 1: Confusing rootDir with include

rootDir determines the root used for output structure. It does not select the project's source files.

Use include or files for initial file selection.

Mistake 2: Assuming TypeScript always stops on errors

TypeScript can emit JavaScript despite type errors.

Use noEmitOnError: true when you want compiler output blocked on errors.

Mistake 3: Mixing module formats

Using CommonJS and native ESM settings inconsistently can cause import errors or runtime failures.

Keep compiler and runtime module configurations aligned.

Mistake 4: Treating transpilation as type checking

Tools such as tsx can execute TypeScript without performing the same complete type checking as tsc.

Run a separate type-checking command when necessary.

7. TypeScript Interview Questions

Q1. Why is local TypeScript installation preferred?

Local installation records the project's compiler dependency. Combined with a lockfile and reproducible installation process, it helps keep development and build environments consistent.

Q2. What is tsconfig.json?

It is TypeScript's project configuration file. It controls source-file selection, compiler behavior, type-checking options, and generated output.

Q3. What is the difference between rootDir and outDir?

rootDir defines the source root used for output structure, while outDir defines where generated files are written.

Q4. What does strict: true do?

It enables a collection of stricter type-checking options that detect additional potentially unsafe type operations.

Q5. What is the purpose of @types/node?

It provides TypeScript declarations for Node.js APIs, enabling type checking, autocomplete, and editor assistance.

Q6. What is the difference between tsc and tsx?

tsc is TypeScript's official compiler for checking types and optionally emitting JavaScript. tsx is primarily a development tool for transforming and executing TypeScript without full semantic type checking.

8. Quick Revision Notes

Commands to remember

Command

Purpose

npm init -y

Initialize the project

npm install -D typescript

Install TypeScript locally

npm install -D @types/node

Add Node.js type declarations

npx tsc --init

Generate tsconfig.json

npx tsc

Compile the project

npx tsc --noEmit

Type-check without output

npm ci

Install dependencies from lockfile

Important configuration options

Option

Remember

rootDir

Source root for emitted structure

outDir

Compiler output directory

target

JavaScript version

module

Module system behavior

strict

Stricter type checking

include

Source-file patterns

noEmitOnError

Block output when errors exist

sourceMap

Debugging source maps

Five things to remember

  1. Prefer local TypeScript installation with a committed lockfile.

  2. tsconfig.json defines how the compiler processes your project.

  3. rootDir organizes emitted file paths; include selects source files.

  4. strict: true enables important additional type checks.

  5. TypeScript compilation, type checking, and application execution are distinct activities.

Final takeaway

A TypeScript project needs more than .ts files.

It needs a consistent compiler dependency, a clear configuration, and a reliable build process.

A well-configured TypeScript project makes development more predictable, type checking more reliable, and collaboration easier.


Further Reading


Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.