📘 TypeScript Fundamentals: The Evolution of JavaScript
JavaScript is arguably the most successful language in human history. However, its greatest strength—its flexibility—is also its fatal flaw in Enterprise environments.
JavaScript is Dynamically (Loosely) Typed.
let total = 100; // It's a number
total = "Hello"; // Now it's a string
total.toFixed(2); // 💥 FATAL CRASH IN PRODUCTION! Strings don't have decimals.
In an enterprise application with 50,000 lines of code, remembering that total was changed to a string 3 files ago is impossible.
TypeScript (TS), built by Microsoft, is a "strict syntactical superset" of JavaScript. It adds Static Typing. If you write TS, the editor will scream at you with red squiggly lines before you even save the file, mathematically preventing entire classes of bugs from ever reaching the user.
1️⃣ How TypeScript Works
Browsers cannot run TypeScript. If you feed app.ts to Chrome, it crashes instantly.
TypeScript is a Compiler. You write .ts files. You run the tsc compiler command. The compiler analyzes your code, ensures the math adds up, strips away all the type definitions, and spits out a safe, standard .js file for the browser to run.
2️⃣ Basic Types & Inference
You declare types in TS by placing a colon : after the variable name.
// Explicit Typing
let age: number = 25;
let username: string = "Mwero";
let isActive: boolean = true;
// Type Error (The TS superpower)
age = "Twenty Five"; // ❌ TS Error: Type 'string' is not assignable to type 'number'.
Type Inference
TypeScript is incredibly smart. If you assign a value immediately, you do NOT need to write the type. TS figures it out automatically.
let score = 100; // TS instantly locks this variable as a 'number' forever.
score = "Hi"; // ❌ Error! It inferred 'number', you can't change it.
3️⃣ Complex Types: Arrays and Tuples
Arrays
// An array that can ONLY hold strings
let hobbies: string[] = ["Reading", "Coding"];
// Type Inference works here too
let numbers = [1, 2, 3]; // Inferred as number[]
numbers.push("Four"); // ❌ Error!
Tuples
A Tuple is a strict array where the exact length and types of specific positions are locked in. (This is exactly how React's useState works under the hood!)
// An array that MUST have exactly 2 elements: a string, then a number.
let employeeRecord: [string, number] = ["Mwero", 50000];
// ❌ Error: Order is wrong
employeeRecord = [50000, "Mwero"];
4️⃣ The Core Superpower: Interfaces
When dealing with Objects, TypeScript provides Interfaces. An Interface is a strict, contractual blueprint. If an object violates the blueprint by missing a property, or using the wrong type, the code refuses to compile.
// 1. Define the Architectural Blueprint
interface User {
id: number;
username: string;
email: string;
// The '?' makes this property optional!
phoneNumber?: string;
}
// 2. Enforce the Contract
const adminAccount: User = {
id: 1,
username: "MweroA",
// ❌ ERROR: Property 'email' is missing in type '{ id: number; username: string; }'
};
Why is this amazing? Autocomplete!
When you type adminAccount. in VS Code, because it is tethered to the User interface, VS Code will instantly open an autocomplete menu displaying exactly id, username, email, and phoneNumber. You never have to guess or check the database documentation again.
5️⃣ Function Typing
Functions are the most dangerous part of raw JavaScript because they accept any arguments in any order. TypeScript locks the input arguments and the output return value.
// parameter1 is a number, parameter2 is a number, the final RETURN value MUST be a number.
function calculateTax(subtotal: number, taxRate: number): number {
return subtotal * taxRate;
}
// ❌ Error: Argument of type 'string' is not assignable to parameter of type 'number'.
calculateTax(100, "fast");
// ❌ Error: Type 'string' is not assignable to type 'number'. (Regarding the return value).
function getGreeting(name: string): number {
return `Hello, ${name}`;
}
If a function is designed to never return anything (like an event listener that just clicks a button and logs to the console), the return type is void.
function logToConsole(message: string): void {
console.log(message);
}
💡 Summary Comparison
| Concept | JavaScript (Lawless) | TypeScript (Strict) |
|---|---|---|
| Mental Model | Variables hold values. | Variables are locked to a strict type of data. |
| Object Data | const user = { a: 1 } | interface User { a: number }; const user: User = ... |
| Catching Bugs | In production, after the user crashes the app. | Instantly, as a red line in VS Code while typing. |
| Autocomplete | None. Editor guesses blindly. | Perfect 100% Intellisense mappings. |