Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Typescript
  4. /Setting Up Typescript
Your Progress0%
0 of 30 completed

TypeScript Topics

Getting Started

  • What is TypeScript?
  • TypeScript vs JavaScript
  • Setting Up TypeScript
  • Your First TypeScript Program

Basic Types

  • Primitive Types
  • Arrays and Tuples
  • Objects and Type Aliases
  • Enums
  • Any, Unknown, and Never

Functions & Interfaces

  • Function Types and Signatures
  • Interfaces
  • Optional and Default Parameters
  • Function Overloading

Advanced Types

  • Union and Intersection Types
  • Type Guards and Narrowing
  • Literal Types
  • Type Assertions and Casting

Generics

  • Introduction to Generics
  • Generic Constraints
  • Utility Types

Classes & OOP

  • Classes and Constructors
  • Access Modifiers
  • Inheritance and Polymorphism
  • Abstract Classes and Interfaces

Practical TypeScript

  • Working with Modules
  • TypeScript with React
  • Async/Await and Promises
  • Working with APIs and JSON
  • Type Declarations and DefinitelyTyped
  • TypeScript Best Practices

Setting Up TypeScript

Installing TypeScript and configuring your development environment

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:

terminal
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:

terminal
# 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.3

Note: 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:

terminal
# 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 typescript

Local 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

terminal
# 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 dist

Your project structure should now look like this:

project-structure
typescript-tutorial/
β”œβ”€β”€ src/          # TypeScript source files (.ts)
β”œβ”€β”€ dist/         # Compiled JavaScript output (.js)
β”œβ”€β”€ package.json  # Project dependencies
└── node_modules/ # Installed packages

Step 2: Initialize TypeScript Configuration

Create a tsconfig.json file to configure TypeScript:

terminal
# Generate default tsconfig.json
npx tsc --init

# This creates a tsconfig.json with sensible defaults

The 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:

tsconfig.json
{
  "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

tsconfig.json
{
  "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

tsconfig.json
{
  "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

tsconfig.json
{
  "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

tsconfig.json
{
  "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:

package.json
{
  "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:

terminal
# 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 clean

Setting Up Your Code Editor

Visual Studio Code (Recommended)

VS Code has built-in TypeScript support and is the most popular choice:

  1. Download VS Code from https://code.visualstudio.com
  2. Install these recommended extensions:
    • ESLint: Code quality and style checking
    • Prettier: Code formatting
    • Error Lens: Inline error display
    • Path Intellisense: Autocomplete file paths
  3. VS Code will automatically use your project's TypeScript version

VS Code Settings for TypeScript

Create a .vscode/settings.json file in your project:

.vscode/settings.json
{
  "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
// 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

terminal
# 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: true

Check the dist/index.js file to see the compiled JavaScript (all types removed):

dist/index.js
// 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:

terminal
# 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.json

Watch Mode for Development

Watch mode automatically recompiles when you save filesβ€”perfect for development:

terminal
# 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

terminal
# Use npx to run locally installed TypeScript
npx tsc

# Or install globally
npm install -g typescript

Issue 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

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

terminal
# 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/react

Quick Start with Project Templates

For faster setup, you can use pre-configured templates:

Create React App with TypeScript

terminal
npx create-react-app my-app --template typescript
cd my-app
npm start

Next.js with TypeScript

terminal
npx create-next-app@latest my-app --typescript
cd my-app
npm run dev

Node.js API with TypeScript

terminal
# 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 --init

Vite with TypeScript

terminal
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev

Verifying Your Setup

Let's verify everything is working correctly:

  1. Check TypeScript is installed:
    terminal
    tsc --version
    # Should show: Version 5.x.x
  2. Check tsconfig.json exists:

    Your project should have a tsconfig.json file

  3. 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
  4. Check editor support:

    Open a .ts file and type const 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) or npm install --save-dev typescript (local)
  • Use npx tsc --init to create a tsconfig.jsonconfiguration file
  • Enable "strict": true in tsconfig.json for better type safety
  • Set rootDir to "./src" and outDir to "./dist" for organized projects
  • Use tsc --watch during 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!

Know someone setting up TypeScript? Share this guide!

Previous
TypeScript vs JavaScript
Next
Your First TypeScript Program

Never Miss a New TypeScript Tutorial

Join 1,000+ developers learning TypeScript step-by-step. Get new tutorials, type safety tips, and exclusive resources delivered to your inbox - completely FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

TypeScript Tutorials

0 of 30 completed

Your Progress0%

Topics

Getting Started

  • What is TypeScript?
  • TypeScript vs JavaScript
  • Setting Up TypeScript
  • Your First TypeScript Program

Basic Types

  • Primitive Types
  • Arrays and Tuples
  • Objects and Type Aliases
  • Enums
  • Any, Unknown, and Never

Functions & Interfaces

  • Function Types and Signatures
  • Interfaces
  • Optional and Default Parameters
  • Function Overloading

Advanced Types

  • Union and Intersection Types
  • Type Guards and Narrowing
  • Literal Types
  • Type Assertions and Casting

Generics

  • Introduction to Generics
  • Generic Constraints
  • Utility Types

Classes & OOP

  • Classes and Constructors
  • Access Modifiers
  • Inheritance and Polymorphism
  • Abstract Classes and Interfaces

Practical TypeScript

  • Working with Modules
  • TypeScript with React
  • Async/Await and Promises
  • Working with APIs and JSON
  • Type Declarations and DefinitelyTyped
  • TypeScript Best Practices
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

Β© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo