TypeScript adds static typing to JavaScript, catching errors early and improving code quality.
Why TypeScript?
TypeScript provides:
- Type safety
- Better IDE support
- Easier refactoring
- Self-documenting code
Basic Types
// Primitives
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
// Arrays
let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ["a", "b", "c"];
// Objects
interface User {
name: string;
age: number;
email?: string; // Optional property
}
const user: User = {
name: "John",
age: 30
};
Functions
function greet(name: string): string {
return `Hello, ${name}!`;
}
// Arrow functions
const add = (a: number, b: number): number => a + b;
// Optional parameters
function log(message: string, userId?: number): void {
console.log(message, userId);
}
Interfaces vs Types
// Interface
interface Point {
x: number;
y: number;
}
// Type alias
type Status = "pending" | "approved" | "rejected";
// Extending interfaces
interface Point3D extends Point {
z: number;
}
Generics
function identity<T>(arg: T): T {
return arg;
}
const result = identity<string>("hello");
// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
Practical Example
interface Product {
id: string;
name: string;
price: number;
}
class ShoppingCart {
private items: Product[] = [];
addItem(product: Product): void {
this.items.push(product);
}
getTotal(): number {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
Next Steps
- Learn advanced types (union, intersection)
- Explore utility types
- Practice with real projects
- Configure tsconfig.json properly