Describe the shape of your objects with precise types, then make them reusable with interfaces.
Open this lesson in KodokonIn 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.
const book: { title: string; pages: number } = {
title: "The Little Prince",
pages: 96,
};
console.log(book.title); // "The Little Prince"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.
interface Recipe {
name: string;
servings: number;
isVegetarian: boolean;
}
const pancakes: Recipe = {
name: "Pancakes",
servings: 4,
isVegetarian: true,
};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.
interface Contact {
name: string;
phone: string;
email?: string; // optional thanks to the ?
}
const alice: Contact = {
name: "Alice",
phone: "0601020304",
}; // allowed: email can be omitted