TypeScript Basics — Types, Interfaces, Generics
972 words
5 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# TypeScript Basics — Types, Interfaces, Generics ## 🎯 Learning Objectives - Understand TypeScript's type system - Define interfaces and type aliases - Use generics for reusable code - Use TypeScript with React components - Understand type narrowing and unions ## 1. What is TypeScript?

TypeScript Basics — Types, Interfaces, Generics
🎯 Learning Objectives
- Understand TypeScript's type system
- Define interfaces and type aliases
- Use generics for reusable code
- Use TypeScript with React components
- Understand type narrowing and unions
1. What is TypeScript?
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds:
- Static typing: Catch errors at compile time, not runtime
- Better tooling: Autocomplete, refactoring, navigation
- Interfaces: Define contracts for object shapes
- Generics: Reusable, type-safe components
2. Basic Types
typescript// Primitives let name: string = 'Alice'; let age: number = 25; let isStudent: boolean = true; let data: any = 'could be anything'; // Avoid when possible let nothing: null = null; let notDefined: undefined = undefined; // Arrays let numbers: number[] = [1, 2, 3]; let names: Array<string> = ['Alice', 'Bob']; // Tuples (fixed-length arrays with types) let pair: [string, number] = ['Alice', 25]; // Enums enum Color { Red, // 0 Green, // 1 Blue // 2 } let c: Color = Color.Green; // 1
3. Interfaces and Type Aliases
typescript// Interface — describes object shape interface User { id: number; name: string; email: string; age?: number; // Optional property readonly createdAt: Date; // Cannot be modified } // Type alias — similar but can represent unions, primitives type Status = 'active' | 'inactive' | 'banned'; type Point = { x: number; y: number }; type Callback = (error: Error | null, result?: any) => void; // Using interfaces function greetUser(user: User): string { return `Hello, ${user.name}!`; } const alice: User = { id: 1, name: 'Alice', email: '[email protected]', createdAt: new Date() };
Interface vs Type:
- Interfaces can be extended (
extends), types cannot - Types can represent unions (
A | B), interfaces cannot - Use interface for object shapes, type for unions/aliases
4. Functions with Types
typescript// Typed function function add(a: number, b: number): number { return a + b; } // Optional and default parameters function greet(name: string, greeting: string = 'Hello'): string { return `${greeting}, ${name}!`; } // Rest parameters function sum(...numbers: number[]): number { return numbers.reduce((total, n) => total + n, 0); } // Function type type MathOperation = (a: number, b: number) => number; const multiply: MathOperation = (x, y) => x * y;
5. Generics
typescript// Generic function function first<T>(arr: T[]): T | undefined { return arr[0]; } const firstNum = first([1, 2, 3]); // number const firstStr = first(['a', 'b']); // string // Generic interface interface ApiResponse<T> { data: T; status: number; message: string; } const userResponse: ApiResponse<User> = { data: { id: 1, name: 'Alice', email: '...', createdAt: new Date() }, status: 200, message: 'OK' }; // Generic constraints function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
6. TypeScript with React
typescript// Typed props interface ButtonProps { label: string; onClick: () => void; variant?: 'primary' | 'secondary'; disabled?: boolean; } const Button: React.FC<ButtonProps> = ({ label, onClick, variant = 'primary', disabled = false }) => { return ( <button onClick={onClick} disabled={disabled} className={`btn btn-${variant}`} > {label} </button> ); }; // Typed state const [count, setCount] = React.useState<number>(0); const [user, setUser] = React.useState<User | null>(null); // Typed event handler function handleChange(e: React.ChangeEvent<HTMLInputElement>) { console.log(e.target.value); }
7. Practice Questions
Q1: What is the difference between interface and type?Answer: Interfaces can be extended (merged) usingextends; types cannot. Types can represent unions (string | number), intersections, and primitives; interfaces represent object shapes. Prefer interfaces for public API objects, types for complex type expressions. Q2: What doesTin a generic function represent?Answer: A type parameter — a placeholder that gets replaced with a concrete type when the function is called.function first<T>(arr: T[]): Tmeans: for any type T, this function takes an array of T and returns a single T. Q3: What is the?operator in an interface property?Answer: It marks the property as optional.age?: numbermeans the property can be present or absent. Accessing it without checking may giveundefined. Q4: How do you type an event handler in React with TypeScript?Answer: Use React event types:typescript<input onChange={(e: React.ChangeEvent<HTMLInputElement>) => { setValue(e.target.value); }} />Q5: What is thereadonlymodifier?Answer: Prevents reassignment of the property after initial creation. Likeconstfor object properties.readonly createdAt: Date— can't setuser.createdAt = new Date(). Q6: What doeskeyof Tdo?Answer: Returns a union of all property keys of T.keyof User='id' | 'name' | 'email' | 'createdAt'. Used with generics to constrain keys to valid properties. Q7: What is union typeA | B?Answer: A value that can be either type A or type B. Example:string | nullmeans a string or null. Use type narrowing (typeof, instanceof, in) to access type-specific features. Q8: Write a typed React component that acceptstitle(string),items(string array), and anonSelectcallback.typescriptinterface ListProps { title: string; items: string[]; onSelect: (item: string) => void; } const List: React.FC<ListProps> = ({ title, items, onSelect }) => ( <div> <h2>{title}</h2> <ul> {items.map((item, i) => ( <li key={i} onClick={() => onSelect(item)}>{item}</li> ))} </ul> </div> );
📐 Key Concepts
| Feature | Syntax | Purpose |
|---|---|---|
| Type annotation | variable: Type | Declare type |
| Interface | interface I { } | Object shape contract |
| Type alias | type T = ... | Union, intersection, primitive |
| Generic | `` | Type-safe reusable code |
| Union | A | B | One of several types |
| Optional | prop?: type | May be undefined |
🔗 Cross-References
- Next: Advanced Flask/Backend Join Discord Previous4.1 React Router & State ManagementNextAdvanced Backend