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
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.