Skip to content

Latest commit

 

History

History
147 lines (101 loc) · 2.68 KB

File metadata and controls

147 lines (101 loc) · 2.68 KB

Tuples in TypeScript

A Tuple is a special array with a fixed number of elements and fixed types in order.

// This is just a normal array (no type restrictions)
let tUser = ["hc", 131, true];

Since you didn't specify types, TypeScript infers it as:

(string | number | boolean)[]

✅ Proper Tuple Declaration

let rgb: [number, number, number] = [255, 255, 255];

This ensures:

  • Only 3 items
  • Each must be a number

Tuple with Custom Type

type MyUser = [number, string];   // Tuple: first number, second string
const newUser12: MyUser = [112, "an"];

⚠ Why .push() is allowed on tuples?

Tuples are arrays internally, so they inherit array methods.

newUser12.push(1);   // Allowed by TS (not desirable)
newUser12.push("2"); // Still allowed

If you want to prevent push, make the tuple readonly:

type MyUser = readonly [number, string];

Now:

newUser12.push(1); // ❌ Error

Looping Over Tuple

newUser12.map(value => console.log(value));

Enums in TypeScript

Enums represent a fixed set of named constants.

Without Enum (Not recommended)

const AISLE = 0;
const MIDDLE = 1;
const WINDOW = 2;

if (seat === AISLE) { }

This works, but is not descriptive.


Basic Enum

enum SeatChoice {
  AISLE,
  MIDDLE,
  WINDOW
}

const hcSeat = SeatChoice.AISLE; // hcSeat = 0 (default numbering)

Enum with Custom Numeric Values

enum MySeatChoice {
  AISLE = 10,
  MIDDLE = 20,
  WINDOW = 30
}

Enum with Mixed Types (Allowed in TypeScript)

enum NewSeatChoice {
  AISLE = "aisle",
  MIDDLE = 20,
  WINDOW = 30
}

const enum (Recommended)

const enum is optimized by the compiler and does not exist at runtime. It replaces enum usage with literal values → faster & smaller code.

const enum NewSeatChoice1 {
  AISLE = "aisle",
  MIDDLE = 20,
  WINDOW = 30
}

const mySeat = NewSeatChoice1.AISLE; // Compiled to "aisle"

Quick Summary Table

Concept What it Means Key Point
Tuple Fixed-length typed array Can lock order & type of items
Normal Array Dynamic length All values share a general type
Enum Named constant values Improves readability & safety
const enum Compile-time optimized enum Removes runtime overhead

If you'd like, I can now convert this entire set into a printable one-page cheat sheet PDF — just tell me:

"Make PDF" 👈