TypeScript ยท Chapter 16 of 44

TypeScript Interfaces

An interface describes the shape of an object: which properties it must have and what type each property is. Interfaces are one of the most common ways to define object types in TypeScript.

When an object is checked against an interface, TypeScript verifies that all required properties are present with the correct types. If a property is missing or has the wrong type, TypeScript reports an error.

Syntax
interface User {
  name: string;
  age: number;
}

Defining an interface

You use the `interface` keyword followed by a name and a block listing property names and types, such as `interface User { name: string; age: number; }`.

Using an interface

Once defined, you can annotate variables, function parameters, or return types with the interface name to enforce that shape wherever it's used.

Example 1 (typescript)
interface User {
  name: string;
  age: number;
}

const user: User = { name: "Lee", age: 22 };
console.log(`${user.name}, ${user.age}`);
Output
Lee, 22

The user object must match the User interface exactly, including both required properties.

Example 2 (typescript)
interface Product {
  title: string;
  price: number;
}

function printProduct(p: Product) {
  console.log(`${p.title}: $${p.price}`);
}
printProduct({ title: "Book", price: 12 });
Output
Book: $12

The function parameter is typed using the Product interface to enforce its shape.

Key points

  • Interfaces describe the required shape of an object.
  • They are defined with the `interface` keyword.
  • TypeScript checks that objects match all required properties and types.
  • Interfaces are commonly used to type function parameters and return values.
๐Ÿ’ก Note: Interfaces can also be extended to build on top of existing ones, similar to inheritance.

๐Ÿ“ Quick Quiz

1. What does an interface describe?

2. Which keyword defines an interface?

3. What happens if an object is missing a required interface property?