Lesson 5
22 min
Describe the shape of an object with interfaces, optional properties and extends.
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.
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.
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 stringAs 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.
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 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);
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.
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.
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.
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,
};
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.
interface Counter {
value: number;
increment(step: number): void;
read(): number;
}
const myCounter: Counter = {
value: 0,
increment(step) {
this.value += step;
},
read() {
return this.value;
},
};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.
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)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.
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 numberThe 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 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.
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.
? makes a property optional, readonly makes it non-modifiable.extends lets you build an interface from another one.Exercise
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
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.