Lab 07: Enums & Namespaces

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Numeric/string/const enums, reverse mapping, enum pitfalls, union type alternatives, namespaces vs modules, ambient declarations.


Step 1: Setup

docker run -it --rm node:20-alpine sh
npm install -g typescript ts-node
mkdir /lab07 && cd /lab07
cat > tsconfig.json << 'EOF'
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true
  }
}
EOF

Step 2: Numeric Enums


Step 3: String Enums


Step 4: Const Enums

💡 const enum produces smaller/faster output but can't be used with isolatedModules.


Step 5: Enum Pitfalls & Union Type Alternatives


Step 6: Namespaces


Step 7: Ambient Declarations


Step 8: Capstone — Enums vs Union Types

Run:

📸 Verified Output:


Summary

Type
Syntax
Reverse Map
Tree-Shakeable
Recommendation

Numeric enum

enum E { A = 1 }

Avoid (unsafe)

String enum

enum E { A = 'A' }

OK for debugging

Const enum

const enum E { A = 1 }

Fast, limited use

Union type

'a' | 'b' | 'c'

N/A

Preferred

Const object

{ A: 'A' } as const

N/A

Best of both

Last updated