Objects, Interfaces, and Type Aliases
Object Type Annotation
Section titled “Object Type Annotation”let user: { name: string; age: number } = { name: "Sahil", age: 22,};This works, but is hard to reuse.
Interface
Section titled “Interface”interface User { name: string; age: number;}Use interfaces to describe object shapes clearly.
Type Alias
Section titled “Type Alias”type User = { name: string; age: number;};Type aliases can also represent unions, tuples, and complex type formulas.
Interface vs Type
Section titled “Interface vs Type”- Great for object-oriented style design
- Supports declaration merging (reopening)
- Common for class contracts
- Works for objects, unions, intersections, tuples
- Better for composing advanced type logic
- Cannot be reopened after declaration
Interface Reopening
Section titled “Interface Reopening”interface User { name: string;}
interface User { age: number;}Now User has both name and age.
Intersection Types
Section titled “Intersection Types”type A = { name: string };type B = { age: number };type Person = A & B;Person must contain both sets of properties.
graph LR
A[Type A] --> C[Intersection Type]
B[Type B] --> C
C --> D[Combined Requirements]
Interfaces with Methods
Section titled “Interfaces with Methods”interface Calculator { add(a: number, b: number): number;}Method signatures keep behavior contracts explicit.