Technology · TypeScript

TypeScript Basics

A starter guide to TypeScript covering types, variables, and basic syntax for newcomers.

TL;DR
  1. 01Add static types to your JavaScript variables and functions.
  2. 02Catch bugs at compile time before code runs.
  3. 03Use the TypeScript compiler to convert to JavaScript.

Setup

  • Install TypeScript globally with npm to get the tsc command.
    npm install -g typescript
  • Run tsc --init to create a tsconfig.json file for your project.
    tsc --init
  • Save your code in files with the .ts extension instead of .js.
  • Compile your TypeScript file by running the compiler with the filename.
    tsc filename.ts
  • Run the generated JavaScript file with Node or in the browser.

Basic Types

  • Use string for text values like names, messages, or any words.
    const name: string = "Sam";
  • Use number for integers and decimals, since there is no separate float type.
    const age: number = 30;
    const price: number = 9.99;
  • Use boolean for true and false values in conditions and flags.
    const isActive: boolean = true;
  • Use any to disable type checking, but try to avoid it.
    let data: any = 42;
    data = "now a string"; // allowed
  • Use unknown for safer code when the type is not yet known.

Variables

  • Declare typed variables with an annotation after the variable name.
    let username: string = "Sam";
  • Skip the annotation and let TypeScript infer the type from the value.
    let count = 5; // inferred as number
  • Use const for values that never change, like config keys or fixed numbers.
    const MAX_RETRIES = 3;
  • Declare arrays using square brackets or the generic Array form.
    const scores: number[] = [10, 20, 30];
    const names: Array<string> = ["A", "B"];
  • Use tuples for arrays with fixed types and length.
    const point: [number, number] = [10, 20];

Functions

  • Add types to parameters and a return type for full safety.
    function add(a: number, b: number): number {
      return a + b;
    }
  • Use void as the return type for functions that do not return anything.
    function log(msg: string): void {
      console.log(msg);
    }
  • Mark optional parameters with a question mark after the name.
    function greet(name?: string) {
      return `Hi ${name ?? "friend"}`;
    }
  • Set default parameter values directly in the function signature.
    function multiply(a: number, b: number = 2) {
      return a * b;
    }
  • Type arrow functions the same way as regular functions for consistency.

Compiler

  • Edit tsconfig.json to control how the TypeScript compiler builds your code.
  • Enable "strict": true to turn on all strict type-checking options at once.
    {
      "compilerOptions": {
        "strict": true,
        "target": "ES2022"
      }
    }
  • Use "target" to choose which JavaScript version the compiler outputs.
  • Run tsc --watch to recompile files every time you save changes.
    tsc --watch
  • Check the outDir setting to control where compiled JavaScript files are saved.

Tip: Let TypeScript infer types when the value is obvious to keep your code clean and readable.

Warning: Avoid the any type whenever possible, since it removes the type safety that TypeScript provides.

TypeScript Classes