TypeScript · 3 minute lesson
Interfaces and type aliases help describe structured objects. A clear shape documents the information a function expects and lets the editor identify missing properties or values with the wrong type. For a learning site, a Lesson interface can connect data loading, cards, and progress features.
A question mark marks an optional property. Code that reads it must account for the possibility that it is undefined. You can provide a fallback with the nullish coalescing operator when a missing value has a sensible default.
Keep object types close to the real data model. A title should be a string because it is text; a duration should be a number because calculations may use it. Type checking verifies code against the declared shape, but it does not inspect an external server response on its own. Validate untrusted data before treating it as a Lesson.
Try the example
interface Lesson {
title: string;
minutes: number;
summary?: string;
}
const lesson: Lesson = { title: "Object types", minutes: 7 };
console.log(lesson.summary ?? "Summary coming soon");Practice
Add a completed boolean property to Lesson and update the object to satisfy the interface. Then write a function that accepts a Lesson and returns its title and duration as one readable string.
Continue learning: Official documentation.