TypeScript Basics

A beginner guide to TypeScript covering static types, variables, functions, and the compiler workflow.

TL;DR

  1. Annotate variables with primitive types like string and number.
  2. Define typed function parameters and explicit void or return shapes.
  3. Run tsc to compile typed code down to clean JavaScript.

Primitive Types

    string

    Represents textual data wrapped in quotes or backticks.

    const username: string = 'Alex';
    const greeting: string = `Hello, ${username}`;
    number

    Handles integers, floating-point decimals, and special numeric values.

    let count: number = 42;
    const price: number = 19.99;
    const hex: number = 0xff;
    boolean

    Stores binary true or false values for conditions.

    let isComplete: boolean = false;
    const hasAccess: boolean = true;
    unknown

    Represents any value safely by requiring type checks.

    let rawInput: unknown = '{"id": 1}';
    if (typeof rawInput === 'string') {
      console.log(rawInput.trim());
    }

Variables and Arrays

    Type Inference

    Infers the type automatically from the assigned value.

    let score = 100; // inferred as number
    // score = 'high'; // Error: Type 'string' invalid
    Array Syntax

    Declares typed collections with square brackets.

    const scores: number[] = [85, 92, 78];
    const names: Array<string> = ['Ada', 'Linus'];
    Tuple Types

    Defines fixed-length arrays with specific element types in order.

    let record: [number, string] = [1, 'Active'];
    record = [2, 'Pending'];
    readonly modifier

    Prevents mutation of array elements after creation.

    const values: readonly number[] = [1, 2, 3];
    // values.push(4); // Error: push does not exist

Functions and Parameters

    Typed Parameters

    Enforces type safety on function inputs and outputs.

    function add(x: number, y: number): number {
      return x + y;
    }
    Optional Parameters

    Marks arguments that can be omitted with a question mark.

    function greet(name: string, title?: string): string {
      return title ? `${title} ${name}` : name;
    }
    Default Parameters

    Provides fallback values for omitted function arguments.

    function multiply(a: number, factor: number = 2) {
      return a * factor;
    }
    void Return

    Signifies that a function returns no meaningful value.

    function logEvent(message: string): void {
      console.log(`[LOG]: ${message}`);
    }

Compiler and Config

    tsc --init

    Generates a starter tsconfig.json file in your project.

    # Initialize TypeScript config
    npx tsc --init
    tsc --watch

    Compiles project files automatically when changes are saved.

    # Start watch mode
    npx tsc --watch
    strict mode

    Turns on all strict compiler checks simultaneously.

    {
      "compilerOptions": {
        "strict": true,
        "target": "ES2022"
      }
    }

Tips

  1. Rely on TypeScript type inference when assigning values to const or let variables to keep your codebase expressive and clean.
  2. Enable the strict flag in tsconfig.json early to prevent subtle runtime bugs and missing null checks.

Warnings

  1. Avoid using the any type because it completely disables compile-time type checking for that value.
  2. Remember that TypeScript type annotations vanish at runtime, meaning you still need typeof checks to validate dynamic API responses.

In Practice

FAQ