TypeScript

Introduction to TypeScript

20 min Lesson 1 of 40

What is TypeScript?

TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. Developed and maintained by Microsoft, TypeScript is a superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. However, TypeScript adds optional static typing, classes, interfaces, and many other features that help developers write more robust and maintainable code.

Key Point: TypeScript code cannot run directly in browsers or Node.js. It must be compiled (or "transpiled") into JavaScript first. The TypeScript compiler removes all TypeScript-specific syntax and produces clean, readable JavaScript code that can run anywhere JavaScript runs.

Why Use TypeScript?

1. Static Type Checking

TypeScript catches type-related errors during development, before your code runs. This means you can find bugs earlier in the development process:

// JavaScript - no error until runtime
function greet(person) {
    return "Hello, " + person.name;
}

greet("John"); // Runtime Error: Cannot read property 'name' of undefined

// TypeScript - error caught during development
function greet(person: { name: string }) {
    return "Hello, " + person.name;
}

greet("John"); // Compile Error: Argument of type 'string' is not assignable

2. Enhanced IDE Support

TypeScript provides excellent autocomplete, intelligent code navigation, and refactoring capabilities. Modern editors like VS Code can provide real-time feedback as you type, showing you available properties and methods, catching typos, and suggesting fixes.

3. Better Code Documentation

Type annotations serve as inline documentation that never gets out of sync with your code. When you see a function signature, you immediately know what types of arguments it expects and what it returns.

// Self-documenting function signature
function calculateDiscount(
    price: number,
    discountPercent: number,
    applyTax: boolean = true
): number {
    let discounted = price * (1 - discountPercent / 100);
    return applyTax ? discounted * 1.1 : discounted;
}

4. Easier Refactoring

When you rename a property or change a function signature, TypeScript will find all the places where you need to update your code. This makes large-scale refactoring much safer and faster.

5. Access to Modern JavaScript Features

TypeScript supports the latest JavaScript features (ES2015+) and allows you to use them even if you need to target older browsers. The compiler will transpile modern syntax into code that works in your target environment.

TypeScript vs JavaScript

Feature JavaScript TypeScript
Typing Dynamic, weakly typed Static, strongly typed (optional)
Error Detection Runtime errors Compile-time errors
Compilation Not required Required (transpiles to JS)
Learning Curve Easier for beginners Requires understanding types
IDE Support Good Excellent
Refactoring Manual, error-prone Automated, safe

Setting Up TypeScript Environment

Prerequisites

Before installing TypeScript, you need to have Node.js and npm (Node Package Manager) installed on your computer. You can download Node.js from nodejs.org. The npm package manager comes bundled with Node.js.

// Check if Node.js is installed
node --version

// Check if npm is installed
npm --version

Installing TypeScript

There are two main ways to install TypeScript:

1. Global Installation (Recommended for Learning)

This installs TypeScript globally on your system, making the tsc (TypeScript Compiler) command available everywhere:

npm install -g typescript

// Verify installation
tsc --version

2. Local Installation (Recommended for Projects)

This installs TypeScript as a development dependency in your project:

// Initialize a new npm project
npm init -y

// Install TypeScript locally
npm install --save-dev typescript

// Verify installation
npx tsc --version

Best Practice: For real projects, always install TypeScript locally as a dev dependency. This ensures everyone on your team uses the same TypeScript version, preventing inconsistencies.

Your First TypeScript File

Let's create a simple TypeScript file and compile it:

Step 1: Create a file named hello.ts:

// hello.ts
function greet(name: string): string {
    return `Hello, ${name}!`;
}

const message = greet("TypeScript");
console.log(message);

Step 2: Compile the TypeScript file:

tsc hello.ts

Step 3: This creates a hello.js file:

// hello.js (generated)
function greet(name) {
    return "Hello, " + name + "!";
}
var message = greet("TypeScript");
console.log(message);

Step 4: Run the JavaScript file:

node hello.js
// Output: Hello, TypeScript!

Notice: The compiled JavaScript has no type annotations. TypeScript removes all type information during compilation, producing clean JavaScript that can run in any JavaScript environment.

Setting Up a TypeScript Project

For larger projects, you'll want to create a proper project structure with a configuration file:

// Create a new project directory
mkdir my-typescript-project
cd my-typescript-project

// Initialize npm
npm init -y

// Install TypeScript
npm install --save-dev typescript

// Create a TypeScript configuration file
npx tsc --init

This creates a tsconfig.json file with many commented options. We'll explore this file in detail in the next lesson.

Recommended Project Structure

my-typescript-project/
├── src/              # TypeScript source files
│   └── index.ts
├── dist/             # Compiled JavaScript files
├── node_modules/     # Dependencies
├── package.json      # Project metadata
└── tsconfig.json     # TypeScript configuration

Watch Mode

During development, you can use watch mode to automatically recompile files when they change:

// Watch a single file
tsc hello.ts --watch

// Watch all files in a project
tsc --watch

TypeScript Playground

Before setting up a local environment, you can experiment with TypeScript in the official online playground at typescriptlang.org/play. This is perfect for trying out small code snippets and seeing how TypeScript compiles to JavaScript.

Practice Exercise

Set up your TypeScript environment and complete these tasks:

  1. Install Node.js and npm if you haven't already
  2. Install TypeScript globally on your system
  3. Create a new directory called typescript-practice
  4. Inside it, create a file called calculator.ts with these functions:
    function add(a: number, b: number): number {
        return a + b;
    }
    
    function subtract(a: number, b: number): number {
        return a - b;
    }
    
    function multiply(a: number, b: number): number {
        return a * b;
    }
    
    function divide(a: number, b: number): number {
        if (b === 0) {
            throw new Error("Cannot divide by zero");
        }
        return a / b;
    }
    
    // Test the functions
    console.log("10 + 5 =", add(10, 5));
    console.log("10 - 5 =", subtract(10, 5));
    console.log("10 * 5 =", multiply(10, 5));
    console.log("10 / 5 =", divide(10, 5));
  5. Compile the file using tsc calculator.ts
  6. Run the compiled JavaScript file using node calculator.js
  7. Try passing a string instead of a number to one of the functions and see what error TypeScript gives you

Summary

  • TypeScript is a superset of JavaScript that adds static typing and other powerful features
  • It catches errors during development rather than at runtime
  • TypeScript code must be compiled to JavaScript before it can run
  • TypeScript provides better IDE support, easier refactoring, and self-documenting code
  • You can install TypeScript globally or locally in your projects
  • The tsc command compiles TypeScript files to JavaScript
  • Every JavaScript file is already valid TypeScript - you can adopt TypeScript gradually

Next Steps: In the next lesson, we'll dive deep into the TypeScript compiler and configuration options, learning how to customize the compilation process to fit your project's needs.