Lesson 3 / 7

Interfaces and Type Aliases

Interfaces

interface Course {n    title: string;n    lessonCount: number;n    isFree?: boolean;   // the ? makes this property optionaln}nnfunction describeCourse(course: Course): string {n    return `${course.title} has ${course.lessonCount} lessons`;n}nndescribeCourse({ title: "TypeScript", lessonCount: 7 });   // isFree can be omitted

An interface describes the shape an object must have — which properties, and what type each one is. Any object matching that shape can be used wherever the interface is expected; TypeScript checks structure, not a formal declared relationship, which is often called “structural typing.”

Type aliases

type ID = number | string;ntype Course = {n    title: string;n    lessonCount: number;n};

type can name anything — a union, a primitive, or an object shape just like an interface. For describing the shape of an object, interface and type are largely interchangeable; a common convention is to prefer interface for object shapes and reserve type for unions and other cases interface cannot express.

Extending an interface

interface CertifiedCourse extends Course {n    certificateName: string;n}

extends lets one interface build on another, the same idea as class inheritance but for describing shapes rather than behavior — a CertifiedCourse must satisfy everything Course requires, plus its own additional property.

readonly properties

interface Course {n    readonly id: number;n    title: string;n}nnconst course: Course = { id: 1, title: "TypeScript" };ncourse.title = "Advanced TypeScript";   // finencourse.id = 2;                          // Error: id is read-only

readonly catches accidental reassignment of a value that should never change after creation, like a database ID, directly at compile time.