interfaces and type aliases
Describing Object Shapes
One of TypeScript's most powerful features is the ability to describe exactly what an object should look like — which properties it has, and what type each one is. This is done with interfaces or type aliases.
Defining an Interface
interface User {
name: string;
age: number;
email: string;
}
const user1: User = {
name: "Alice",
age: 28,
email: "alice@example.com"
};If user1 is missing a property, has an extra one, or has the wrong type for a field, TypeScript will raise a compile-time error.
Optional Properties
Use ? to mark a property as optional.
interface User {
name: string;
age: number;
phone?: string; // optional
}
const user2: User = { name: "Bob", age: 34 }; // valid, phone omittedReadonly Properties
Use readonly to prevent a property from being changed after the object is created.
interface Point {
readonly x: number;
readonly y: number;
}
const origin: Point = { x: 0, y: 0 };
origin.x = 10; // Error: Cannot assign to 'x' because it is a read-only propertyInterfaces with Methods
interface Greetable {
name: string;
greet(): void;
}
const person: Greetable = {
name: "Charlie",
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};Extending Interfaces
An interface can build on top of another using extends, inheriting all its properties.
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const myDog: Dog = { name: "Rex", breed: "Labrador" };Type Aliases
A type alias does something similar to an interface, using the type keyword. It can describe objects, unions, primitives, and more.
type User = {
name: string;
age: number;
};
type ID = string | number;
type Status = "active" | "inactive" | "pending";Interface vs Type Alias — Quick Comparison
| Interface | Type Alias |
|---|---|
| Can only describe object shapes | Can describe objects, unions, primitives, tuples, etc. |
Supports extends for combining interfaces | Supports intersections with & instead |
| Can be re-opened and merged with the same name | Cannot be redeclared once defined |
| Preferred for defining object/class contracts | Preferred for unions and utility compositions |
Best practice: Useinterfacewhen describing the shape of objects or classes, andtypewhen you need unions, intersections, or aliasing simpler types.
Nested Object Types
interface Address {
street: string;
city: string;
}
interface User {
name: string;
address: Address;
}
const user3: User = {
name: "Dana",
address: { street: "123 Main St", city: "Springfield" }
};
Coming up next: Arrays and tuples — how TypeScript strengthens list-like data structures.