Type Aliases and Interfaces
Introduction
In the beginning, types were quite different from interfaces.
Over the years, forum discussions and posts would happen from time to time about the differences, pros and cons of each one. As new versions of TypeScript would be released, those posts and pieces of advice would become outdated.
As of TypeScript 4 (maybe earlier), there is not much difference between interfaces and type aliases. What you can do with one, you can do with the other (albeit with different approaches).
The main difference as of TypeScript 5.x is that interfaces allow for declaration merging.
Example interface vs type alias
interface IPerson {
id: number;
name: string;
};
// (1)
interface IStudent extends IPerson {
email: string;
}
const student1: IStudent = {
id: 1,
name: "Aayla Secura",
email: "aayla@jedischool.dev",
};
type TPerson = {
id: number;
name: string;
};
// (2)
type TStudent = TPerson & { email: string };
const student2: TStudent = {
id: 2,
name: "Ahsoka Tano",
email: "ahsoka@jedischool.dev",
};
1 | Using extends to create another interface from a base interface. |
2 | Using the intersection operator & to compose together the two types. |
The intersection behaves more like an union operation this example. Read more on Intersection Types and Union Types. |