TypeScript Documentation

Welcome to the official documentation for TypeScript, a superset of JavaScript that adds static types. TypeScript enables you to write robust and scalable JavaScript applications.

TypeScript compiles down to plain JavaScript, which runs anywhere JavaScript runs. You can use TypeScript in any browser, on any host, and on any operating system.

Key Benefit TypeScript helps you catch errors early in the development cycle by providing static type checking, improving code quality and maintainability.

TypeScript Basics

Types

TypeScript allows you to define the types of your variables, function parameters, and return values. This helps prevent type-related errors.

Common built-in types include:

  • string
  • number
  • boolean
  • array
  • object
  • any (use with caution)
  • void
  • null
  • undefined
  • enum
  • tuple
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];

Variables

You can declare variables with specific types or let TypeScript infer them. The let, const, and var keywords work similarly to JavaScript, with let and const being preferred for block-scoping.

let message: string = "Hello, TypeScript!";
const PI: number = 3.14159;

Functions

Define function signatures with parameter types and return types for improved clarity and safety.

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

let myGreeting = greet("World"); // myGreeting is inferred as string

Arrow functions are also fully supported:

const add = (a: number, b: number): number => a + b;

Interfaces

Interfaces define the shape of objects. They are a powerful way to define contracts for your code.

interface Person {
    name: string;
    age?: number; // Optional property
    readonly id: number; // Readonly property
}

function printName(person: Person): void {
    console.log(person.name);
}

let user: Person = { name: "Alice", id: 123 };
printName(user);

Classes

TypeScript's classes are similar to JavaScript classes but with added features like access modifiers (public, private, protected) and explicit type annotations.

class Animal {
    public name: string;
    private age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    move(distanceInMeters: number = 0): void {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

let cat = new Animal("Whiskers", 2);
cat.move(10);
// console.log(cat.age); // Error: Property 'age' is private.

Advanced Topics

Generics

Generics provide a way to create reusable components that can work over a variety of types rather than a single one. They are a form of polymorphism.

function identity<T>(arg: T): T {
    return arg;
}

let output1 = identity<string>("myString"); // type: string
let output2 = identity<number>(100);       // type: number

Decorators

Decorators are a special kind of declaration that can be attached to classes, methods, accessors, properties, or parameters. They are an experimental feature.

Decorators are a form of metaprogramming that allows you to add annotations and meta-programming syntax for classes and members.

function sealed(constructor: Function) {
    Object.seal(constructor);
    Object.seal(constructor.prototype);
}

@sealed
class BuggyClass {
    // ...
}

Modules

TypeScript supports JavaScript's module systems (ES Modules and CommonJS). Modules help organize code into reusable pieces and prevent naming conflicts.

Example (ES Module):

// file: math.ts
export function add(x: number, y: number): number {
    return x + y;
}

// file: main.ts
import { add } from "./math";
console.log(add(5, 3)); // Output: 8

Async Programming

TypeScript seamlessly integrates with JavaScript's asynchronous patterns like Promises and async/await, providing type safety for asynchronous operations.

async function fetchData(url: string): Promise<any> {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
}

async function processData() {
    try {
        const data = await fetchData("https://api.example.com/data");
        console.log("Data fetched:", data);
    } catch (error) {
        console.error("Failed to fetch data:", error);
    }
}
processData();

Tooling

TypeScript comes with a powerful command-line interface (CLI) for compiling TypeScript to JavaScript. It also integrates with popular build tools like Webpack, Rollup, and Parcel, and is supported by most modern IDEs (VS Code, WebStorm, etc.) with excellent IntelliSense and refactoring capabilities.

To compile TypeScript, you'll typically use the tsc command:

npm install -g typescript
tsc your_file.ts

For project-level compilation, a tsconfig.json file is used to configure compiler options.

Ecosystem

TypeScript has a thriving ecosystem. Many popular JavaScript libraries and frameworks provide TypeScript definitions, allowing you to use them with full type safety.

The npm registry is the primary source for TypeScript-enabled packages and type definition files (often found in the @types/ scope).

Library/Framework TypeScript Support
React Excellent (@types/react)
Angular Built-in
Vue.js Excellent (@vue/runtime-core, etc.)
Node.js Excellent (@types/node)
Express.js Excellent (@types/express)