Lesson 5 / 1242%

Lesson 5

Objects and Interfaces

22 min

Describe the shape of an object with interfaces, optional properties and extends.

What is a typed object?

Definition

An object groups several named values, called properties. An interface is the description of an object's shape: it lists the name and type of each expected property, without creating any value.

Almost all real-world data has the shape of an object: a user, a product, an order. Describing this shape with TypeScript lets the editor offer autocompletion and immediately flag a typo or an incorrect type.

Typing an object

You can describe an object's shape directly, by listing the name and type of each of its properties. TypeScript then checks that the object respects this shape: no unknown property, no wrong type.

object.ts
const user: { name: string; age: number } = {
  name: "Lea",
  age: 25,
};

user.age = 26;      // OK
user.email = "x";   // Error: property email does not exist
user.name = 42;     // Error: number is not assignable to string

As with simple variables, you don't have to write this annotation: if you create the object directly, TypeScript infers its shape from the values. The annotation becomes useful when the object is received as a function parameter.

Interfaces

When the same shape is used in several places, you name it with an interface. It is the most common way to describe objects in TypeScript. By convention, the name starts with a capital letter.

interface.ts
interface User {
  name: string;
  age: number;
  email: string;
}

const lea: User = {
  name: "Lea",
  age: 25,
  email: "lea@example.com",
};

function display(u: User) {
  console.log(u.name + " (" + u.age + " years old)");
}

display(lea);
Diagram: the User interface with its properties listed in the box.

An interface only exists for TypeScript: it disappears completely at compilation and therefore adds no code to the final program. Don't confuse it with a class, which does produce JavaScript code. Here, User serves only as a contract that lea and the display function must respect.

Optional and read-only properties

  • ? after the name makes the property optional: it can be missing (its type then becomes the original type or undefined).
  • readonly forbids modifying the property after the object is created.
optional.ts
interface Product {
  readonly id: number;
  name: string;
  description?: string;
}

const book: Product = { id: 1, name: "TypeScript Guide" };

book.name = "Complete Guide"; // OK
book.id = 2;                  // Error: id is read-only

// The type of description is string | undefined
console.log(book.description?.toUpperCase());

The ?. operator used on the last line is called optional chaining: it calls toUpperCase only if the description exists, and returns undefined otherwise. Without it, TypeScript would reject the code, because the value may be missing.

Nesting and extending interfaces

An interface can use another one as a property type, and you can create a new one from an existing one with extends. The new interface takes all the properties of the old one and adds new ones.

extends.ts
interface Address {
  street: string;
  city: string;
}

interface Person {
  name: string;
  address: Address;
}

interface Employee extends Person {
  salary: number;
}

const emp: Employee = {
  name: "Tom",
  address: { street: "1 Peace Street", city: "Paris" },
  salary: 2500,
};
Diagram: the Employee interface extending Person, with its properties listed in the box.

Describing methods

A property of an interface can also be a function. You then describe the types of its parameters and of its return value, exactly as for an ordinary function.

methods.ts
interface Counter {
  value: number;
  increment(step: number): void;
  read(): number;
}

const myCounter: Counter = {
  value: 0,
  increment(step) {
    this.value += step;
  },
  read() {
    return this.value;
  },
};

Objects as parameters and return values

Interfaces really make sense with functions: a parameter typed with an interface forces the caller to provide a complete object, and the return type guarantees the shape of what is returned. Autocompletion then works inside the function as well as outside.

function.ts
interface Article {
  title: string;
  price: number;
}

function applyDiscount(a: Article, rate: number): Article {
  return { title: a.title, price: a.price * (1 - rate) };
}

const pen: Article = { title: "Pen", price: 2 };
const sale = applyDiscount(pen, 0.25);
console.log(sale.price); // 1.5 (number)

Free-named properties: the index signature

Sometimes you don't know the property names in advance, for example for a dictionary of scores. The index signature then describes the type of the keys and the type of the values. Here, every key of type string must be associated with a number.

index.ts
interface Scores {
  [player: string]: number;
}

const ranking: Scores = { Lea: 120, Tom: 95 };
ranking.Sara = 130;        // OK
ranking.Max = "absent";    // Error: string is not assignable to number

interface or type?

The type keyword can also name an object's shape, with a very similar syntax. To describe objects, the two are equivalent in the vast majority of cases. Just remember: interface for objects and classes, type for everything else (unions, tuples, computed types), as we will see soon.

type_alias.ts
type Point = {
  x: number;
  y: number;
};

const origin: Point = { x: 0, y: 0 };

Good to know

TypeScript is a structural type system: an object is accepted as soon as it has the right shape, even if it wasn't declared with the interface. What matters is the shape, not the name.

Warning

When you write an object directly where the type is expected, TypeScript rejects extra properties: const p: Point = { x: 1, y: 2, z: 3 } is an error. This check, known as excess property checking, helps catch typos.

Good habits with interfaces

Give each interface a singular name that describes a single thing (User, not Users), and group them in a dedicated file as soon as they are shared between several files. Prefer small, precise interfaces that you combine with extends, rather than one big interface where half the properties are optional.

Finally, reserve ? for information that is truly optional. An optional property forces all the code that uses it to handle the case where it is missing: the more there are, the heavier the code becomes to write and read. A well-designed interface serves as documentation: by reading it, another developer immediately understands what data flows through the program, without having to read the rest of the code.

Summary

  • An object groups named properties, each with its own type.
  • An interface names an object shape and can be reused anywhere.
  • ? makes a property optional, readonly makes it non-modifiable.
  • extends lets you build an interface from another one.
  • Typing is structural: only the shape matters, not the name of the type.

Exercise

Create a Book interface with a title, an author, a year and an optional number of pages. Then create an array of three books and a function that displays the title and author of each one.

Going further

Create a Student interface that extends Person with a read-only array of grades. Write a function that takes a student and returns their average, then try to modify the grades array to see the error.