TypeScript Introduction
TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript.
Why TypeScript?
- Type Safety: Catch errors at compile time, not runtime
- Better IDE support: Autocompletion, refactoring, navigation
- Self-documenting: Types serve as inline documentation
- Scalability: Essential for large codebases
- Modern JS: All ES6+ features + types
Basic Types
// Primitives
let name: string = "Alice";
let age: number = 30;
let active: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;
// Arrays
let scores: number[] = [95, 87, 92];
let langs: Array<string> = ["TypeScript", "Python"];
// Tuple
let pair: [string, number] = ["Alice", 30];
// Any (avoid!) and Unknown (safer)
let data: unknown = fetchData();
// Union types
let id: string | number = "abc123";
// Literal types
let direction: "north" | "south" | "east" | "west" = "north";
let status: 200 | 201 | 400 | 404 | 500 = 200;
Interfaces
interface User {
id: string;
name: string;
email: string;
age?: number; // optional
readonly createdAt: Date; // readonly
}
interface Admin extends User {
role: "admin";
permissions: string[];
}
// Usage
const user: User = {
id: "u_001",
name: "Alice",
email: "alice@example.com",
createdAt: new Date(),
};
Type Aliases
// Object type
type Point = { x: number; y: number };
// Function type
type Transformer<T> = (value: T) => T;
// Union
type StringOrNumber = string | number;
// Intersection
type AdminUser = User & { role: "admin" };
Generics
// Generic function
function identity<T>(value: T): T {
return value;
}
identity<string>("hello"); // type: string
identity<number>(42); // type: number
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
// Generic with constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Utility Types
interface User {
id: string;
name: string;
email: string;
password: string;
}
// Partial - all optional
type UpdateUser = Partial<User>;
// Required - all required
type FullUser = Required<User>;
// Pick - select fields
type PublicUser = Pick<User, "id" | "name" | "email">;
// Omit - exclude fields
type SafeUser = Omit<User, "password">;
// Readonly
type ImmutableUser = Readonly<User>;
// Record
type RoleMap = Record<string, string[]>;