Kodokon kodokon.com

Objects and interfaces

Describe the shape of your objects with precise types, then make them reusable with interfaces.

8 min · 3 questions

Open this lesson in Kodokon

In JavaScript, an object groups several related pieces of information as key-value pairs, like a record card: a book has a title and a number of pages. In TypeScript, you can describe the exact shape of an object: which properties it contains and what type each one is.

TYPESCRIPT
const book: { title: string; pages: number } = {
  title: "The Little Prince",
  pages: 96,
};

console.log(book.title); // "The Little Prince"
The object's shape is written directly in the type.

Writing the shape out every time quickly becomes repetitive. An interface gives that shape a name, so you can reuse it everywhere. You declare it with the interface keyword, followed by a name (capitalized by convention), then the list of properties and their types.

TYPESCRIPT
interface Recipe {
  name: string;
  servings: number;
  isVegetarian: boolean;
}

const pancakes: Recipe = {
  name: "Pancakes",
  servings: 4,
  isVegetarian: true,
};
The Recipe interface describes every recipe in the program.

All the properties of an interface are required by default: forgetting servings would trigger an error. To make a property optional, add a question mark ? right after its name. The object can then be created with or without that property.

TYPESCRIPT
interface Contact {
  name: string;
  phone: string;
  email?: string; // optional thanks to the ?
}

const alice: Contact = {
  name: "Alice",
  phone: "0601020304",
}; // allowed: email can be omitted
email? makes the property optional.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is an interface for in TypeScript?
    • To describe the shape of an object and reuse it
    • To create a web page
    • To run a function faster
    • To store data on a server
  2. What does the question mark in email?: string mean?
    • The email property is required
    • The email property is optional
    • The email property is always empty
  3. An object typed as Recipe is missing the name property. What happens?
    • TypeScript reports an error before execution
    • The program crashes without warning at runtime
    • TypeScript adds the property automatically