TypeScript Course

TypeScript Variables and Type System

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Type Annotations

TypeScript lets you annotate variables with their types. The compiler infers types when you don't annotate explicitly.

let name: string = "Alice";
let age: number = 25;
let isActive: boolean = true;
let data: null = null;
let value: undefined = undefined;

// Type inference — TypeScript figures it out
let city = "London";      // inferred as string
let count = 42;           // inferred as number

Arrays and Tuples

const numbers: number[] = [1, 2, 3, 4, 5];
const names: Array = ["Alice", "Bob"];

// Tuple — fixed-length array with known types
const point: [number, number] = [10, 20];
const entry: [string, number] = ["score", 95];

Union Types

let id: string | number;
id = "abc-123";  // OK
id = 42;         // OK
// id = true;    // ❌ Error

function printId(id: string | number) {
    if (typeof id === "string") {
        console.log(id.toUpperCase());
    } else {
        console.log(id.toFixed(2));
    }
}

Literal Types and Type Aliases

type Direction = "up" | "down" | "left" | "right";
type Status = "pending" | "approved" | "rejected";

let move: Direction = "up";   // OK
// move = "diagonal";          // ❌ Error

type Point = { x: number; y: number };
const origin: Point = { x: 0, y: 0 };

any, unknown, never

let anything: any = "hello";   // disables type checking
anything = 42;                 // OK

let safe: unknown = getData(); // must narrow before using
if (typeof safe === "string") {
    console.log(safe.toUpperCase());
}

function fail(msg: string): never {  // never returns
    throw new Error(msg);
}