TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds static type checking to catch errors during development.

Why TypeScript?

  • Catch type errors before runtime
  • Better IDE autocomplete and refactoring
  • Self-documenting code through types
  • Gradual adoption — add types incrementally

Basic Types

  let name: string = 'Alice';
let age: number = 25;
let active: boolean = true;
let ids: number[] = [1, 2, 3];
let tuple: [string, number] = ['Alice', 25];

let anything: any = 'could be anything'; // avoid when possible
let unknownValue: unknown = getInput();  // safer than any
  

Functions

  function add(a: number, b: number): number {
    return a + b;
}

const greet = (name: string): string => `Hello, ${name}`;

function log(message: string): void {
    console.log(message);
}
  

Interfaces

  interface User {
    id: number;
    name: string;
    email?: string; // optional
    readonly createdAt: Date;
}

function displayUser(user: User): void {
    console.log(user.name);
}
  

Type Aliases and Unions

  type ID = string | number;
type Status = 'pending' | 'active' | 'archived';

function setStatus(status: Status) {
    console.log(status);
}
  

Generics

  function wrap<T>(value: T): T[] {
    return [value];
}

interface ApiResponse<T> {
    data: T;
    error: string | null;
}

async function fetchUser(): Promise<ApiResponse<User>> {
    // ...
}
  

Classes

  class Animal {
    constructor(protected name: string) {}

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

class Dog extends Animal {
    bark(): void {
        console.log('Woof!');
    }
}
  

Type Narrowing

  function process(value: string | number) {
    if (typeof value === 'string') {
        console.log(value.toUpperCase());
    } else {
        console.log(value.toFixed(2));
    }
}
  

Using TypeScript with JavaScript

Rename .js to .ts gradually, or use JSDoc in .js files:

  /** @param {number} a @param {number} b @returns {number} */
function add(a, b) {
    return a + b;
}
  

Setup

  npm install -D typescript
npx tsc --init
npx tsc
  

tsconfig.json essentials:

  {
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "outDir": "./dist",
    "moduleResolution": "node"
  },
  "include": ["src/**/*"]
}
  

When to Adopt

Scenario Recommendation
Large team/codebase Strong yes
Small scripts Optional
React/Angular projects Usually included
Learning JavaScript Learn JS first, then TS

TypeScript does not replace JavaScript fundamentals — it enhances them with a type system that scales with project complexity.