What is TypeScript?
TypeScript is JavaScript with types:
- Catches errors at compile time
- Better IDE support
- Self-documenting code
- Compiles to JavaScript
Basic Types
// Primitives
const name: string = "Alice";
const age: number = 30;
const active: boolean = true;
// Arrays
const numbers: number[] = [1, 2, 3];
const names: Array<string> = ["Alice", "Bob"];
// Any (avoid if possible)
let data: any = "anything";
// Unknown (safer than any)
let input: unknown = getValue();
Type Inference
TypeScript infers types when obvious:
const name = "Alice"; // Inferred as string
const age = 30; // Inferred as number
const items = [1, 2, 3]; // Inferred as number[]
Functions
// Parameter and return types
function greet(name: string): string {
return `Hello, ${name}!`;
}
// Arrow functions
const add = (a: number, b: number): number => a + b;
// Optional parameters
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
// Default parameters
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
Interfaces
interface User {
name: string;
email: string;
age?: number; // Optional
}
const user: User = {
name: "Alice",
email: "alice@example.com"
};
// Function with interface
function createUser(data: User): User {
return { ...data };
}
Types
// Type alias
type ID = string | number;
// Union types
type Status = "pending" | "active" | "deleted";
// Intersection types
type Admin = User & { role: "admin" };
Generics
// Generic function
function identity<T>(value: T): T {
return value;
}
identity<string>("hello");
identity<number>(42);
// Generic interface
interface Response<T> {
data: T;
status: number;
}
const response: Response<User> = {
data: { name: "Alice", email: "a@b.com" },
status: 200
};
Classes
class User {
private id: number;
public name: string;
protected email: string;
constructor(id: number, name: string, email: string) {
this.id = id;
this.name = name;
this.email = email;
}
greet(): string {
return `Hello, I'm ${this.name}`;
}
}
// Shorthand
class User {
constructor(
private id: number,
public name: string,
protected email: string
) {}
}
Type Guards
function isString(value: unknown): value is string {
return typeof value === "string";
}
function process(value: string | number) {
if (typeof value === "string") {
// TypeScript knows it's a string here
return value.toUpperCase();
}
// TypeScript knows it's a number here
return value * 2;
}
Utility Types
interface User {
name: string;
email: string;
age: number;
}
// Partial - all properties optional
type PartialUser = Partial<User>;
// Required - all properties required
type RequiredUser = Required<User>;
// Pick - select properties
type UserName = Pick<User, "name">;
// Omit - exclude properties
type UserWithoutAge = Omit<User, "age">;
// Record - object type
type UserMap = Record<string, User>;
Common Patterns
Props and Components
interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
}
function Button({ label, onClick, disabled }: ButtonProps) {
return (
<button onClick={onClick} disabled={disabled}>
{label}
</button>
);
}
API Responses
interface ApiResponse<T> {
data: T;
error?: string;
status: number;
}
async function fetchUser(id: string): Promise<ApiResponse<User>> {
const res = await fetch(`/api/users/${id}`);
return res.json();
}
Event Handlers
function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
console.log(event.target);
}
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event.target.value);
}
Configuration
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist"
},
"include": ["src/**/*"]
}
Tips
Start Gradually
// Start with basic types
const name: string = "Alice";
// Add interfaces for objects
interface Config {
apiUrl: string;
timeout: number;
}
Use Strict Mode
Enable strict: true for maximum type safety.
Don't Overuse Any
// Bad
const data: any = fetchData();
// Better
const data: unknown = fetchData();
if (isUser(data)) {
// Now typed as User
}
Conclusion
TypeScript benefits:
- Catch errors early
- Better tooling support
- Self-documenting code
- Safer refactoring
Start with basic types, add interfaces gradually.
Next: React Basics - Component-based UI