Why TypeScript?
TypeScript adds static type checking to JavaScript. It catches errors at compile time instead of runtime, improves IDE support, and makes code self-documenting.
Basic Types
let name: string = 'Alice';
let age: number = 25;
let isActive: boolean = true;
let items: string[] = ['a', 'b'];
let mixed: (string | number)[] = [1, 'two', 3];
// Object types
interface User {
id: number;
name: string;
email: string;
role?: 'admin' | 'user'; // Optional
}
const user: User = {
id: 1,
name: 'Alice',
email: 'alice@example.com'
};
Functions
function add(a: number, b: number): number {
return a + b;
}
function greet(name: string, greeting?: string): string {
return `${greeting || 'Hello'}, ${name}!`;
}
// Arrow functions
const multiply = (a: number, b: number): number => a * b;
Generics
function identity(arg: T): T {
return arg;
}
identity<string>('hello'); // 'hello'
identity<number>(42); // 42
interface ApiResponse {
data: T;
status: number;
message: string;
}
async function fetchData(url: string): Promise> {
const res = await fetch(url);
return res.json();
}
Utility Types
interface User {
id: number;
name: string;
email: string;
password: string;
}
// Make all properties optional
type PartialUser = Partial;
// Make all properties required
type RequiredUser = Required;
// Pick specific properties
type UserBasic = Pick;
// Omit specific properties
type UserWithoutPassword = Omit;
// Record type
type UserMap = Record;
Type Assertions
const input = document.getElementById('name') as HTMLInputElement;
input.value = 'Hello';
// When you know more than TypeScript
const data = JSON.parse(response) as User;