You are viewing a free preview of this lesson.
Subscribe to unlock all 12 lessons in this course and every other course on LearningBro.
Interfaces and type aliases are two of TypeScript's most fundamental tools for describing the shapes of objects, function signatures, and complex data structures. Understanding when to use each — and how they differ — is key to writing idiomatic TypeScript.
An interface defines the shape of an object. It specifies which properties and methods an object must have and what types they should be:
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: 'Alice',
email: 'alice@example.com',
};
Use the ? suffix to mark a property as optional:
interface Config {
host: string;
port: number;
ssl?: boolean; // optional
timeout?: number; // optional
}
const config: Config = {
host: 'localhost',
port: 3000,
// ssl and timeout are not required
};
Mark properties as readonly to prevent reassignment after creation:
interface Point {
readonly x: number;
readonly y: number;
}
const origin: Point = { x: 0, y: 0 };
// origin.x = 5; // Error: Cannot assign to 'x' because it is a read-only property
Interfaces can extend one or more other interfaces, inheriting their properties:
interface Animal {
name: string;
sound: string;
}
interface Pet extends Animal {
owner: string;
}
const dog: Pet = {
name: 'Rex',
sound: 'Woof',
owner: 'John',
};
You can extend multiple interfaces at once:
interface Timestamps {
createdAt: Date;
updatedAt: Date;
}
interface SoftDeletable {
deletedAt: Date | null;
}
interface DatabaseRecord extends Timestamps, SoftDeletable {
id: number;
}
A unique feature of interfaces is declaration merging. If you declare an interface with the same name twice, TypeScript merges them:
interface Window {
title: string;
}
interface Window {
appVersion: string;
}
// The merged interface now has both properties:
// interface Window { title: string; appVersion: string; }
This is particularly useful when augmenting third-party library types.
A type alias creates a new name for any type — primitives, unions, tuples, objects, or anything else:
type ID = string | number;
type Coordinate = [number, number];
type Callback = (data: string) => void;
type UserProfile = {
id: ID;
name: string;
bio: string;
};
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.