Loading lessons...
Static vs Dynamic Typing
JavaScript is dynamically typed, meaning variable types are checked at runtime. TypeScript brings static typing, checking variable types during compilation.
Comparison Overview
| Aspect | Dynamic Typing (JavaScript) | Static Typing (TypeScript) |
|---|---|---|
| Type Checking | Occurs at runtime | Occurs at compile time |
| Variable Reassignment | Variable can hold any type at any time | Variable has a fixed or constrained type |
| Bug Discovery | Users may trigger runtime errors | Developer discovers errors while editing |
| Build Step | No compilation needed | Compilation step required |
Example Code Comparison
In JavaScript:
javascript
let user = "Alice";
user = 42; // Allowed in JS, can cause unexpected bugs downstream
console.log(user.toUpperCase()); // Runtime TypeError: user.toUpperCase is not a function
In TypeScript:
typescript
let user: string = "Alice";
user = 42; // Error: Type 'number' is not assignable to type 'string'.
TL;DR
- Dynamic languages check types during execution; static languages check types during compilation.
- Static typing catches bug classes like misspelled properties and null pointer references early.