🏠 Home / Hub

🔷 TypeScript Lesson 01 — Types & Variables

← Back to TypeScript Menu  |  🏠 Hub

1. TypeScript ဆိုတာ ဘာလဲ

TypeScript = JavaScript + Static Types
Microsoft ကနေ develop, 2012 release

TypeScript → compile → JavaScript (browser/Node run)
Type errors ကို code ရေးတုန်း ဖမ်းနိုင် (runtime မဟုတ်)

🔷 Angular = TS only | React, Vue = TS optional but recommended
// JavaScript — error runtime မှာ ပဲ သိ
function greet(name) {
  return "Hello, " + name.toUpperCase();
}
greet(123);   // Runtime ERROR: name.toUpperCase is not a function

// TypeScript — error ရေးတုန်းကတည်းက သိ
function greet(name: string): string {
  return "Hello, " + name.toUpperCase();
}
greet(123);  // ❌ TS Error: Argument of type 'number' is not assignable to parameter of type 'string'

2. Primitive Types

// Explicit type annotations
let name:    string  = "Ko Ko";
let age:     number  = 25;
let active:  boolean = true;
let nothing: null    = null;
let missing: undefined = undefined;

// TS can infer types (no annotation needed if initializing)
let city    = "Yangon";    // inferred: string
let score   = 95;          // inferred: number
let isAdmin = false;       // inferred: boolean

// Once inferred, type is LOCKED
city = "Mandalay";   // ✅ string OK
city = 123;          // ❌ Error: Type 'number' not assignable to 'string'

// Special types
let anything: any    = "hello";   // ❌ avoid — defeats purpose
anything = 123;                   // no error (but no type safety either)

let flexible: unknown = "hello";  // ✅ safer — must type-check before use
if (typeof flexible === "string") {
  console.log(flexible.toUpperCase());  // OK now
}

let neverReturn: never;   // functions that never return (throw or infinite loop)

3. Union & Literal Types

// Union type — multiple allowed types
let id: string | number = "abc";
id = 123;          // also OK

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

// Literal types — exact values only
type Direction = "north" | "south" | "east" | "west";
let go: Direction = "north";   // ✅
let go2: Direction = "up";     // ❌ Error!

type StatusCode = 200 | 201 | 400 | 401 | 403 | 404 | 500;
let code: StatusCode = 200;

// Boolean literal
type YesNo = "yes" | "no";
type Booleans = true | false;   // same as boolean

4. Arrays & Tuples

// Array types
let names:   string[]  = ["Ko", "Ma", "Aung"];
let scores:  number[]  = [95, 87, 92];
let mixed:   (string | number)[] = ["Ko", 25, "Ma", 30];

// Generic array syntax (same result)
let nums: Array<number> = [1, 2, 3];

// Array methods — TypeScript infers types
names.push("Nwe");         // ✅ string
names.push(123);           // ❌ Error
const upper = names.map(n => n.toUpperCase());  // string[] inferred

// Tuple — fixed length, fixed types at each position
let point: [number, number] = [10, 20];
let entry: [string, number] = ["Ko Ko", 25];

point[0];    // number
entry[1];    // number

// Named tuple (more readable)
type RGB = [red: number, green: number, blue: number];
const white: RGB = [255, 255, 255];
const [r, g, b] = white;   // destructure

5. Type Aliases & Enums

// type alias — reusable type name
type UserRole = "admin" | "editor" | "viewer";
type ID = string | number;

let role: UserRole = "admin";
let userId: ID = 1;

// Enum — named constants (avoid overusing)
enum Status {
  Pending   = "pending",
  Active    = "active",
  Suspended = "suspended",
  Deleted   = "deleted"
}

let userStatus: Status = Status.Active;

// Numeric enum (default)
enum Priority {
  Low    = 1,   // default starts at 0
  Medium = 2,
  High   = 3
}
console.log(Priority.High);  // 3

// const enum — compile-time only (lighter)
const enum Direction { Up, Down, Left, Right }
let d = Direction.Up;  // compiles to: let d = 0;
💡 type alias = recommended | enum = use for fixed sets like Status, Direction, Priority

← TypeScript Menu  |  Next: TS 02 → Interfaces →

📌 Study Checklist