Interfaces are one of TypeScript’s core features, allowing developers to flexibly and expressively enforce constraints on their code to reduce bugs and improve code readability. Let’s dive into exploring the various characteristics of interfaces and how we might better leverage them in our programs.
Jump ahead:
What are TypeScript interfaces?
First, a little background. Interfaces are a way for developers to name a type for later reference in their programs. For example, a public library’s management software might have a Book
interface for data representing books in the library’s collection:
interface Book { title: string; author: string; isbn: string; }
With it, we can ensure that book data in the program contains the essential information of title, author, and ISBN. If it doesn’t, the TypeScript compiler will throw an error:
const tale: Book = { title: 'A Tale of Two Cities', author: 'Charles Dickens', // Error: Property 'isbn' is missing in type '{ title: string; author: string; }' but required in type 'Book'. };
In our Book
interface example above, all the attributes are defined as required. However, we can also define an interface to expect some optional attributes. This can be done by adding the ?
symbol in the attribute definition.
To demonstrate this, let’s add an optional boolean attribute signedCopy
to our Book
interface:
interface Book { title: string; author: string; isbn: string; signedCopy?: boolean; }
Interfaces vs. types
If you’ve written TypeScript code before, you might be familiar with type aliases, another common way to name a type, and you might ask, “Why use interfaces over types or vice versa?”
The primary difference is that interfaces can be reopened for adding additional properties (via declaration merging) in different parts of your program, while type aliases cannot. Let’s look at how to take advantage of declaration merging, as well as some cases of when you might want to.
Expanding interfaces in TypeScript
Option 1: Declaration merging
As noted above, interfaces can be reopened to add new properties and expand the definition of the type. Here is a nonsensical example to illustrate this capability:
interface Stock { value: number; } interface Stock { tickerSymbol: string; }
Of course, it’s not likely that the same interface would be reopened nearby like this. It would be clearer to define it in a single statement:
interface Stock { value: number; tickerSymbol: string; }
So, when would you want to expand an interface in different parts of your program? Let’s look at a real-world use case.
Declaration merging to wrangle disparate user preferences
Suppose you are writing a React application, and you need some pages that will allow the user to configure information such as their profile, notification preferences, and accessibility settings.
For clarity and user experience, you’ve split up these three concerns into three separate pages where the source code will be in three files: Profile.tsx
, Notifications.tsx
, and Accessibility.tsx
.
From an application architecture perspective, it would be nice if all the user’s preferences were contained in a single object that adheres to an interface we’ll call Preferences
. This way, you can easily load and save the preferences object with your backend API with just one or two endpoints rather than several.
The next question is: “Where should the Preferences
interface be defined?” You could put the interface in its own file, preferences.ts
, and import
it into the three pages — or, you could take advantage of declaration merging and have each page define only the properties of Preferences
that it cares about, like so:
// Profile.tsx interface Preferences { avatarUrl: string; username: string; } const Profile = (props) => { // ... UI for managing the user's profile ... }
// Notifications.tsx interface Preferences { smsEnabled: boolean; emailEnabled: boolean; } const Notification = (props) => { // ... UI for managing the user's notification preferences ... }
// Accessibility.tsx interface Preferences { highContrastMode: boolean; } const Accessibility = (props) => { // ... UI for managing the user's accessibility settings ... }
In the end, the Preferences
interface will resolve to fully contain all the properties, as desired:
interface Preferences { avatarUrl: string; username: string; smsEnabled: boolean; emailEnabled: boolean; highContrastMode: boolean; }
The UI code is now co-located with only the properties of Preferences
it manages, making the program easier to understand and maintain. Nice!
Option 2: Extending interfaces in TypeScript
Another way to expand interfaces in TypeScript is to mix one or more of them into a new interface:
interface Pet { name: string; age: number; } interface Dog extends Pet { breed: string; } interface Fish extends Pet { finColor: string; } const betta: Fish = { name: 'Sophie', age: 2, finColor: 'black', };
This probably looks familiar to object-oriented programmers. However, interfaces offer a key feature that is not typically found in traditional object-oriented programming: multiple inheritance.
Extending multiple interfaces in TypeScript
Multiple inheritance allows us to combine behaviors and properties of multiple interfaces into a single interface.
Extending multiple interfaces refers to the concept of composition where the interface is designed to extend attributes it needs. It differs from the concept of inheritance in OOP where an object is a child of a given class and compulsorily extends the parent’s properties.
Let’s look at a use case for when you might want to do this.
Extending interfaces to form a type-safe global state store
Suppose that you’re building an application that enables users to keep track of their to-do lists and their daily schedules in one place. You’ll have some different UI components for tracking each of those tasks:
// todo-list.ts interface ToDoListItem { title: string; completedDate: Date | null; } interface ToDoList { todos: ToDoListItem[]; } // ... application code for managing to-do lists ...
// calendar.ts interface CalendarEvent { title: string; start: Date; end: Date; } interface Calendar { events: CalendarEvent[]; } // ... application code for managing the calendar ...
Now that you’ve created the basic interfaces for keeping track of your two pieces of state, you would like a single interface that represents the state of the entire application. We can use the extends
keyword to create such an interface. We’ll also add a modified
field so that we know when our state was last updated:
interface AppState extends ToDoList, Calendar { modified: Date; }
Now you can use the AppState
interface to ensure that the application is properly handling the state:
function persist(state: AppState) { // ... save the state to a storage layer ... } persist({ todos: [ { title: 'Text Marcy', completedDate: new Date('2022-02-05') }, { title: 'Buy groceries', completedDate: null }, ], events: [ { title: 'Study', start: new Date('2022-02-11 08:00:00'), end: new Date('2022-02-11 10:00:00'), }, ], modified: new Date('2022-02-06'), });
Extending types
While re-opening interfaces is not possible with type aliases, this approach of extending types is, but with some subtle differences in syntax. Here’s the equivalent example adapted to use type
instead of interface
:
type ToDoListItem = { title: string; completedDate: Date | null; } type ToDoList = { todos: ToDoListItem[]; } type CalendarEvent = { title: string; start: Date; end: Date; } type Calendar = { events: CalendarEvent[]; } type AppState = ToDoList & Calendar & { modified: Date; } function persist(state: AppState) { // ... save the state to a storage layer ... } persist({ todos: [ { title: 'Text Marcy', completedDate: new Date('2022-02-05') }, { title: 'Buy groceries', completedDate: null }, ], events: [ { title: 'Study', start: new Date('2022-02-11 08:00:00'), end: new Date('2022-02-11 10:00:00'), }, ], modified: new Date('2022-02-06'), });
The process of combining multiple type definitions is called intersection and is performed using the &
symbol. Learn more by reading up on powerful type options in TypeScript.
Use cases for interfaces in TypeScript
Interfaces can be used to define the expected properties — both required and optional — of a function or class. Let’s take a look at a few use cases.
Using interfaces for functions
We can use an interface to specify the expected parameters and results of a function:
// function interface Person { firstName: string lastName: string age?: number } interface Bio { fullName: string yearOfBirth?: number } function getBio(person: Person): Bio { let yearOfBirth: number // is initially undefined if (person?.age) { const today = new Date() yearOfBirth = today.getFullYear() - person.age } return { fullName: `${person.firstName} ${person.lastName}`, yearOfBirth } }
In our example above, we defined an interface Person
. This Person
object has the required properties firstName
and lastName
along with an optional property age
, which is the expected function parameter.
We also defined an interface Bio
with a required property fullName
and an optional property yearOfBirth
, which the function returns.
Using interfaces for class definitions
We can define an interface for a class that specifies its expected properties and their shapes, then using the implements
keyword to apply this definition to the class:
interface Animal { name: string canWalk(): boolean } class Cat implements Animal { name: string constructor() { this.name = 'Cat' } canWalk() { return true } } const cat = new Cat() console.log(cat.canWalk())
In our example above, we have defined an interface Animal
that the class Cat
implements. This means Cat
must have all the required properties defined in Animal
.
Pros and cons of interfaces in TypeScript
When we discuss the pros and cons of interfaces, we are — to a large extent — discussing the pros and cons of TypeScript versus JavaScript. This is because typing and defining shapes via interfaces is a core feature of TypeScript.
Let’s start with the pros.
With TypeScript interfaces, we define what is expected and give our code some level of consistency and dependability. By setting the type of variables, function parameters, or function results, we know what to expect and will get some compile-time errors alerting us that something not allowed is happening.
In the example below, our JavaScript function does not use a type to describe what is expected, which can lead to unexpected results:
// JavaScript function (a, b) => a + b
// TypeScript function (a: number, b: number): number => a + b
A possible error in our JavaScript example is passing a string instead of a number. The outcome would be a string result (from concatenation) where a number was expected.
More great articles from LogRocket:
- Don't miss a moment with The Replay, a curated newsletter from LogRocket
- Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
- Use React's useEffect to optimize your application's performance
- Switch between multiple versions of Node
- Discover how to animate your React app with AnimXYZ
- Explore Tauri, a new framework for building binaries
- Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Compile-time errors in TypeScript occur at build time and, most importantly, before the function or code is run. This means errors are detected much sooner and before they can cause any damage.
Finally, using interfaces to define code shapes makes the code base easier to manage. By extension, this also has the potential to improve overall performance when working in a team.
Now, let’s explore some drawbacks of using interfaces in TypeScript.
It is easy to rely entirely on interfaces and types to prevent errors and have a false sense of security. While it helps to define the shapes of what is expected — and not expected — it isn’t bulletproof.
Additionally, implementing types and interfaces can very easily and quickly complicate a code base. Just think about functions that take and handle different shapes or types of variables and the endless function overloading that can easily follow.
Conclusion
There are a few different ways to extend object-like types with interfaces in TypeScript, and, sometimes, you may use type aliases.
In those cases, even the official docs say they are mostly interchangeable, at which point it’s down to style, preference, organization, habit, etc. But if you’d like to declare different properties on the same type in different parts of your program, use TypeScript interfaces.
LogRocket: Full visibility into your web and mobile apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.
Try it for free.
Option 0: composition over inheritance – frankly the best option of all. 🙂