TypeScript vs JavaScript – Key Differences with Examples:
| Feature | JavaScript | TypeScript |
|---|---|---|
| Type System | Dynamically typed | Statically typed (with optional annotations) |
| Compilation | Interpreted in browser (no compile step) | Compiled to JavaScript before running |
| Error Detection | Errors are found at runtime | Errors are caught at compile-time |
| OOP Support | Limited | Strong (supports interfaces, generics, etc.) |
| Tooling | Basic | Advanced IDE support with autocompletion, refactoring |
1. Type Safety
JavaScript:
function greet(name) {
return "Hello " + name;
}
greet(5); // Works, but may cause unexpected output
TypeScript:
function greet(name: string): string {
return "Hello " + name;
}
greet(5); // ❌ Error: Argument of type 'number' is not assignable to parameter of type 'string'
2. Interfaces and Type Checking
TypeScript Only:
interface Person {
name: string;
age: number;
}
function printPerson(p: Person) {
console.log(p.name + " is " + p.age);
}
printPerson({ name: "John", age: 30 }); // ✅
printPerson({ name: "John" }); // ❌ Error: Property 'age' is missing
3. ES6+ Features Compatibility
TypeScript: Supports latest ECMAScript features and compiles them to older JS versions:
const greet = (name: string = "Guest"): string => `Hello, ${name}`;
4. Tooling and IntelliSense
TypeScript enables code suggestions, type inference, and error checking in editors like VS Code, improving developer productivity and reducing bugs.
Conclusion:
TypeScript is a superset of JavaScript that adds optional static typing and advanced features for building large-scale applications with more safety and better tooling.