TS TypeScript

Variables & Types

Lesson 2 of 5 ~7 min

Variables are how you store data in your programs. TypeScript gives you two keywords for declaring variables and a rich system of types to describe what data they hold.

let vs const

let count = 0;      // Can be reassigned
count = 1;          // ✅ This works

const pi = 3.14;    // Cannot be reassigned
pi = 3;              // ❌ Error: Assignment to constant variable

Primitive types

let name: string = "Alice";        // string
let age: number = 30;              // number (integers and floats)
let isStudent: boolean = false;    // boolean
let nothing: null = null;          // null
let notDefined: undefined = undefined; // undefined

Arrays & tuples

// Array of numbers — both syntaxes work
let scores: number[] = [95, 87, 92];
let names: Array<string> = ["Alice", "Bob"];

// Tuple — a fixed-length array with specific types at each position
let person: [string, number] = ["Alice", 30];

Union types

Sometimes a variable could be one of several types. A union type lets you express this:

let value: string | number;
value = "hello";  // ✅
value = 42;       // ✅
value = true;     // ❌ Error: Type 'boolean' is not assignable

any, unknown, and never

// any — disables type checking (avoid when possible)
let anything: any = "hello";
anything = 42; // ✅ No error, but no safety either

// unknown — safer alternative to any, requires type checking
let input: unknown = "hello";
if (typeof input === "string") {
  console.log(input.toUpperCase()); // ✅ Safe after check
}

// never — represents a value that never occurs
function throwError(msg: string): never {
  throw new Error(msg);
}

Type aliases

You can create custom type names with the type keyword:

type ID = string | number;
type Point = [number, number];

let userId: ID = "abc123";
let coordinates: Point = [10, 20];
Editor
TypeScript
Console

        

Quiz

Which keyword should you use for a variable that won't be reassigned?
Challenge

Create a union type called Status that accepts string or number. Declare a variable of that type and assign it different values to see how it works.