Typescript Study Chapter ยท Official ReferenceAfzaal Suleman Knowledge Base
TypeScript provides two main ways to define custom types: interfaces and type aliases. While they often achieve similar results, they have distinct use cases and capabilities.
Key Differences
- Interfaces: Can be extended, can implement multiple interfaces, better for object shapes
- Types: Can create unions, intersections, primitives, more flexible for complex types
๐ป
Code Demonstration & Syntax
typescript
// Interface - extensible
interface User {
name: string;
age: number;
}
interface AdminUser extends User {
permissions: string[];
}
// Type - flexible for unions
type ID = string | number;
type Status = "active" | "inactive" | "pending";
// Type - intersection
type Employee = User & {
employeeId: string;
};Output
// No output - type definitions only
๐
Chapter Rules & Key Notes
๐ก
Remember This
- Use interfaces for object shapes that might be extended
- Use type aliases for unions, intersections, and primitive aliases
- Both can be used in most cases, but interfaces are preferred for public APIs
๐
Important Rules
- Prefer interfaces when defining object shapes that need extension
- Use types for unions, intersections, and complex type compositions
- Interfaces support declaration merging, types do not
โ ๏ธ
Common Mistakes
- Using types when interfaces would be more appropriate for object shapes
- Not leveraging declaration merging with interfaces
- Overcomplicating with type intersections when simple extension would work
โฆโฆโฆ