AI Hints
Home›Angular Tutorial›Why TypeScript, Basic Types and Interfaces
Angular · Lesson 12 of 120

Interfaces

The shape of an object.

⏱ 2 min read▶ Video at 13:50🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Most data in an app comes as objects, like a book, with a title, an author, and a price. An interface describes the shape of an object.

  • Data comes as objects
  • A book
  • An interface describes it

What an interface does

An interface lists the properties an object must have, with their types. It has no code, and doesn't exist at run time. It's only a promise, that TypeScript checks. We'll describe our books, users, and orders this way.

keyvalue
Listsproperties and their types
No codeonly a description
Checkedwhen you create objects
We'll useBook, User, Order

A Book interface

Book has a title, an author, and a price. Dune is declared as a Book, so it must match the shape. Describe takes any Book, and builds a sentence. Run it. The book is described, in one line.

main.tstypescript
interface Book {
  title: string;
  author: string;
  price: number;
}

const dune: Book = { title: "Dune", author: "Frank Herbert", price: 9.99 };

function describe(book: Book): string {
  return `${book.title} by ${book.author}, £${book.price}`;
}

console.log(describe(dune));
Output
Dune by Frank Herbert, £9.99
Also uses _mode
ts

When the shape is wrong

Emma has no price. And Circe has an extra property, pages, that Book doesn't have. Run it. TypeScript finds both. Price is missing for Emma. And pages doesn't exist in type Book.

main.tstypescript
interface Book {
  title: string;
  author: string;
  price: number;
}

const emma: Book = { title: "Emma", author: "Jane Austen" };
const circe: Book = { title: "Circe", author: "Madeline Miller", price: 10.99, pages: 400 };
Output
main.ts(7,7): error TS2741: Property 'price' is missing in type '{ title: string;
author: string; }' but required in type 'Book'.
main.ts(8,80): error TS2353: Object literal may only specify known properties, and
'pages' does not exist in type 'Book'.
Also uses _mode
ts

Summary

An interface describes the shape of an object, and TypeScript checks every object against it. That's how we'll describe our books. Next, classes.

Key takeaways
  • interface Book
  • Missing properties
  • Extra properties
Next up: Classes — blueprints for objects