TypeScript is a statically-typed superset of JavaScript developed by Microsoft. Angular uses TypeScript for the following benefits:
1. Static typing — Catch type errors at compile time rather than runtime.
// JavaScript — error only discovered at runtime
function add(a, b) { return a + b; }
add(1, '2'); // Returns '12' (string concatenation — silent bug)
// TypeScript — error caught immediately by the compiler
function addNumbers(a: number, b: number): number { return a + b; }
// addNumbers(1, '2'); ERROR: Argument of type 'string' is not assignable to 'number'
2. Interfaces & Types — Define contracts for data structures.
interface User {
id: number;
name: string;
email: string;
role?: 'admin' | 'user'; // Optional union type
}
3. Decorators — Enable Angular\'s metadata system (@Component, @Injectable, @Input, etc.).
4. Better IDE support — Rich autocompletion, inline documentation, and refactoring tools.
5. Access modifiers — public, private, protected enforce encapsulation.
6. Generics — Write reusable, type-safe code.
getItems<T>(url: string): Observable<T[]> {
return this.http.get<T[]>(url);
}
↥ back to top