TypeScript
Beginner
1 min read
Type Aliases vs Interfaces
Example
// Type alias for an object shape
type Point = {
x: number;
y: number;
};
// Type alias for a union — interfaces cannot do this
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function divide(a: number, b: number): Result<number> {
if (b === 0) return { success: false, error: "Division by zero" };
return { success: true, data: a / b };
}
const r = divide(10, 2);
if (r.success) console.log(r.data); // 5
// Type alias for a primitive (useful for documentation)
type UserID = number;
type Email = string;
// Type alias for a tuple
type Pair<A, B> = [A, B];
const entry: Pair<string, number> = ["score", 98];
// Interface extension vs type intersection
interface Base { id: number }
interface Extended extends Base { name: string } // interface
type BaseType = { id: number };
type ExtendedType = BaseType & { name: string }; // type alias
// Both work the same for object shapes
const a: Extended = { id: 1, name: "A" };
const b: ExtendedType = { id: 2, name: "B" };
// Only type aliases can express mapped types
type Optional<T> = { [K in keyof T]?: T[K] };
type PartialPoint = Optional<Point>; // { x?: number; y?: number }
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript