Setting up TypeScript is straightforward and takes only a few minutes. You'll install the TypeScript compiler, configure your project, and set up your code editor for the best development experience. Let's get your TypeScript environment ready!
Prerequisites
Before installing TypeScript, you need:
- Node.js: TypeScript requires Node.js (version 14 or higher recommended)
- npm or yarn: Package manager (comes with Node.js)
- Code Editor: Visual Studio Code is highly recommended (free and excellent TypeScript support)
- Basic Terminal Knowledge: Running commands in your terminal or command prompt
Check if Node.js is Installed
Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and run:
node --version
npm --version
# You should see version numbers like:
# v18.17.0
# 9.6.7π» Don't Have Node.js?
Download and install Node.js from https://nodejs.org
Choose the LTS (Long Term Support) version for stability.
TypeScript Installation Methods
There are two main ways to install TypeScript:
Method 1: Global Installation (For Learning)
Install TypeScript globally on your computer to use it anywhere:
# Using npm
npm install -g typescript
# Or using yarn
yarn global add typescript
# Verify installation
tsc --version
# You should see something like: Version 5.3.3Note: Global installation is great for learning and small projects. For production projects, use local installation (Method 2) to ensure consistent versions across your team.
Method 2: Local Installation (For Projects)
Install TypeScript as a project dependency:
# Create a new project folder
mkdir my-typescript-project
cd my-typescript-project
# Initialize npm project
npm init -y
# Install TypeScript as dev dependency
npm install --save-dev typescript
# Or using yarn
yarn add --dev typescriptLocal installation keeps TypeScript version-controlled per project, which is essential for team collaboration.
Setting Up Your First TypeScript Project
Let's create a complete TypeScript project from scratch with proper configuration:
Step 1: Create Project Structure
# Create project folder
mkdir typescript-tutorial
cd typescript-tutorial
# Initialize npm
npm init -y
# Install TypeScript locally
npm install --save-dev typescript
# Create folder structure
mkdir src
mkdir distYour project structure should now look like this:
typescript-tutorial/
βββ src/ # TypeScript source files (.ts)
βββ dist/ # Compiled JavaScript output (.js)
βββ package.json # Project dependencies
βββ node_modules/ # Installed packagesStep 2: Initialize TypeScript Configuration
Create a tsconfig.json file to configure TypeScript:
# Generate default tsconfig.json
npx tsc --init
# This creates a tsconfig.json with sensible defaultsThe tsconfig.json file is TypeScript's configuration file. It tells the compiler how to process your TypeScript code and where to output JavaScript files.
Step 3: Configure tsconfig.json
Replace the generated tsconfig.json with this beginner-friendly configuration:
{
"compilerOptions": {
/* Language and Environment */
"target": "ES2020", // JavaScript version to compile to
"lib": ["ES2020"], // JavaScript libraries to include
/* Modules */
"module": "commonjs", // Module system (Node.js style)
"rootDir": "./src", // Source files location
"outDir": "./dist", // Output JavaScript location
/* JavaScript Support */
"allowJs": false, // Don't allow .js files (TypeScript only)
"checkJs": false, // Don't type-check .js files
/* Emit */
"sourceMap": true, // Generate .map files for debugging
"removeComments": true, // Remove comments in output
/* Type Checking */
"strict": true, // Enable all strict type checks
"noImplicitAny": true, // Error on 'any' type
"strictNullChecks": true, // Strict null/undefined checks
"strictFunctionTypes": true, // Strict function type checks
"noUnusedLocals": true, // Error on unused variables
"noUnusedParameters": true, // Error on unused parameters
"noImplicitReturns": true, // Error if not all paths return
/* Completeness */
"skipLibCheck": true, // Skip type checking of .d.ts files
"esModuleInterop": true, // Better module compatibility
"forceConsistentCasingInFileNames": true // Consistent file naming
},
"include": ["src/**/*"], // Files to compile
"exclude": ["node_modules", "dist"] // Files to ignore
}βοΈ Configuration Explained
- target: JavaScript version to compile to (ES2020 works everywhere)
- module: Module system (commonjs for Node.js)
- rootDir/outDir: Where source and output files go
- strict: Enables all strict type checking (highly recommended!)
- sourceMap: Helps with debugging compiled code
Understanding tsconfig.json Options
Let's explore the most important configuration options in detail:
Target and Module Options
{
"compilerOptions": {
// Which JavaScript version to compile to
"target": "ES2020", // ES5, ES6, ES2015, ES2016, ES2020, ESNext
// Which module system to use
"module": "commonjs", // commonjs (Node), ES2015, ES2020, ESNext
}
}Strict Type Checking
{
"compilerOptions": {
// Master switch - enables all strict options
"strict": true,
// Individual strict options (enabled by strict: true)
"noImplicitAny": true, // Disallow 'any' type without explicit annotation
"strictNullChecks": true, // null and undefined handled strictly
"strictFunctionTypes": true, // Function parameter/return type checking
"strictPropertyInitialization": true, // Class properties must be initialized
"noImplicitThis": true, // 'this' must have explicit type
"alwaysStrict": true // Parse in strict mode, emit "use strict"
}
}Recommendation: Always use "strict": true! It catches more bugs and helps you write better TypeScript. Starting with strict mode is easier than enabling it later in a large project.
Module Resolution
{
"compilerOptions": {
"rootDir": "./src", // Where TypeScript files are
"outDir": "./dist", // Where JavaScript files go
"baseUrl": "./", // Base for module resolution
"paths": { // Path aliases (optional)
"@/*": ["src/*"]
}
},
"include": ["src/**/*"], // Which files to compile
"exclude": ["node_modules", "dist", "**/*.test.ts"] // Which to ignore
}Additional Helpful Options
{
"compilerOptions": {
"sourceMap": true, // Generate .map files for debugging
"declaration": true, // Generate .d.ts type declaration files
"removeComments": true, // Remove comments from output
"noEmitOnError": true, // Don't compile if there are errors
"esModuleInterop": true, // Better CommonJS/ES modules compatibility
"resolveJsonModule": true, // Import JSON files
"skipLibCheck": true // Skip type checking of library .d.ts files
}
}Setting Up npm Scripts
Add helpful scripts to your package.json for easier development:
{
"name": "typescript-tutorial",
"version": "1.0.0",
"description": "Learning TypeScript",
"main": "dist/index.js",
"scripts": {
"build": "tsc", // Compile TypeScript
"build:watch": "tsc --watch", // Compile and watch for changes
"start": "node dist/index.js", // Run compiled JavaScript
"dev": "tsc && node dist/index.js", // Build and run
"clean": "rm -rf dist" // Clean output folder
},
"keywords": ["typescript"],
"author": "Your Name",
"license": "ISC",
"devDependencies": {
"typescript": "^5.3.3"
}
}Now you can use these commands:
# Compile TypeScript to JavaScript
npm run build
# Compile and watch for changes (recompiles automatically)
npm run build:watch
# Run the compiled JavaScript
npm run start
# Build and run in one command
npm run dev
# Clean the dist folder
npm run cleanSetting Up Your Code Editor
Visual Studio Code (Recommended)
VS Code has built-in TypeScript support and is the most popular choice:
- Download VS Code from
https://code.visualstudio.com - Install these recommended extensions:
- ESLint: Code quality and style checking
- Prettier: Code formatting
- Error Lens: Inline error display
- Path Intellisense: Autocomplete file paths
- VS Code will automatically use your project's TypeScript version
VS Code Settings for TypeScript
Create a .vscode/settings.json file in your project:
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}π‘ VS Code Features
- IntelliSense: Automatic code completion as you type
- Error Highlighting: See errors immediately in editor
- Go to Definition: Jump to type definitions (F12)
- Refactoring: Rename symbols across files safely
- Debugging: Built-in debugger with breakpoints
Other Editor Options
TypeScript also works well with:
- WebStorm: Paid IDE with excellent TypeScript support
- Sublime Text: With TypeScript plugin
- Vim/Neovim: With coc-tsserver or built-in LSP
- Atom: With atom-typescript package
Creating Your First TypeScript File
Let's create a simple TypeScript file to test your setup:
// src/index.ts - Your first TypeScript file!
// Function with type annotations
function greet(name: string): string {
return `Hello, ${name}! Welcome to TypeScript.`;
}
// Variables with types
const userName: string = "Yusuf";
const age: number = 25;
const isLearning: boolean = true;
// Call the function
const message: string = greet(userName);
console.log(message);
// Log additional info
console.log(`Age: ${age}`);
console.log(`Currently learning: ${isLearning}`);
// This will cause a TypeScript error (uncomment to see):
// greet(123); // Error: Argument of type 'number' is not assignable to parameter of type 'string'Compile and Run
# Compile TypeScript to JavaScript
npm run build
# You should see a new file: dist/index.js
# Run the compiled JavaScript
npm run start
# Output:
# Hello, Yusuf! Welcome to TypeScript.
# Age: 25
# Currently learning: trueCheck the dist/index.js file to see the compiled JavaScript (all types removed):
// Compiled JavaScript (types removed)
"use strict";
function greet(name) {
return `Hello, ${name}! Welcome to TypeScript.`;
}
const userName = "Yusuf";
const age = 25;
const isLearning = true;
const message = greet(userName);
console.log(message);
console.log(`Age: ${age}`);
console.log(`Currently learning: ${isLearning}`);Essential TypeScript Compiler Commands
The TypeScript compiler (tsc) has many useful commands:
# Compile all files in project
tsc
# Compile specific file
tsc src/index.ts
# Compile and watch for changes
tsc --watch
# or
tsc -w
# Compile without emitting files (check for errors only)
tsc --noEmit
# Show compiler version
tsc --version
# Get help
tsc --help
# Initialize tsconfig.json
tsc --init
# Compile with specific config file
tsc --project tsconfig.production.jsonWatch Mode for Development
Watch mode automatically recompiles when you save filesβperfect for development:
# Start watch mode
npm run build:watch
# Leave this running in your terminal
# It will recompile automatically when you save files
# Output:
# [12:00:00] Starting compilation in watch mode...
# [12:00:01] Found 0 errors. Watching for file changes.Common Setup Issues and Solutions
Issue 1: "tsc: command not found"
Problem: Terminal doesn't recognize tsccommand
Solution: Either install TypeScript globally or usenpx tsc for local installations
# Use npx to run locally installed TypeScript
npx tsc
# Or install globally
npm install -g typescriptIssue 2: Compilation Errors
Problem: TypeScript shows type errors
Solution: This is normal! TypeScript is catching bugs. Read the error message and fix the type issues.
Issue 3: Files Not Compiling
Problem: tsc doesn't compile your files
Solution: Check your include and exclude patterns in tsconfig.json
{
// Make sure your source files are included
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}Issue 4: Module Not Found
Problem: "Cannot find module" errors
Solution: Install type definitions or adjust module resolution
# Install type definitions for Node.js
npm install --save-dev @types/node
# Install type definitions for other libraries
npm install --save-dev @types/express
npm install --save-dev @types/reactQuick Start with Project Templates
For faster setup, you can use pre-configured templates:
Create React App with TypeScript
npx create-react-app my-app --template typescript
cd my-app
npm startNext.js with TypeScript
npx create-next-app@latest my-app --typescript
cd my-app
npm run devNode.js API with TypeScript
# Using Express
mkdir my-api
cd my-api
npm init -y
npm install express
npm install --save-dev typescript @types/node @types/express
npx tsc --initVite with TypeScript
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run devVerifying Your Setup
Let's verify everything is working correctly:
- Check TypeScript is installed:terminal
tsc --version # Should show: Version 5.x.x - Check tsconfig.json exists:
Your project should have a
tsconfig.jsonfile - Compile a test file:terminal
# Create and compile a test file echo 'const message: string = "TypeScript works!";' > src/test.ts tsc # Should create dist/test.js - Check editor support:
Open a
.tsfile and typeconst x: string =- you should see autocomplete suggestions
All working? Congratulations! Your TypeScript development environment is ready. You can now start writing TypeScript code with confidence!
Key Takeaways
- Install TypeScript with
npm install -g typescript(global) ornpm install --save-dev typescript(local) - Use
npx tsc --initto create atsconfig.jsonconfiguration file - Enable
"strict": truein tsconfig.json for better type safety - Set
rootDirto"./src"andoutDirto"./dist"for organized projects - Use
tsc --watchduring development for automatic recompilation - VS Code provides excellent built-in TypeScript support
- Install
@types/packages for type definitions of JavaScript libraries - Project templates (Create React App, Next.js, Vite) provide pre-configured TypeScript setups
What's Next?
Now that your TypeScript environment is set up and configured, you're ready to write your first TypeScript program! In the next lesson, we'll create a complete TypeScript application from scratch, compile it, and run it. You'll see TypeScript in action and understand the development workflow.
Get ready to write type-safe code and experience the benefits of TypeScript firsthand!