Type Aliases vs Interfaces
7 min read
Welcome back, coder! π
If you hang around TypeScript forums long enough, youβll witness a battle as old as time (well, since 2012): type vs interface.
It is the specific "Tabs vs Spaces" of the TypeScript world.
Today, we are going to demystify these two heavyweights. We will learn how to create custom structures, understand why they both exist, and decide which one you should actually use in your production code.
Let's dive in! β
1. Creating Custom Types with the type Keyword
The Problem: Repetitive "Inline" Typing
Imagine you are building a user management system. You need to pass a User object to multiple functions. Without custom types, your code looks like this:
// β The "Copy-Paste" Nightmare
function registerUser(user: { id: string; name: string; email: string }) {
console.log("Registering " + user.name);
}
function deleteUser(user: { id: string; name: string; email: string }) {
console.log("Deleting " + user.name);
}
function getUserProfile(user: { id: string; name: string; email: string }) {
// ...
}This violates the DRY (Don't Repeat Yourself) principle. If you decide to add an age property later, you have to update it in three different places. If you miss one, your app breaks.
The Solution: Type Aliases
A Type Alias allows you to give a name to any type definition. You define the shape once and reuse the name everywhere.
Think of it like saving a phone number in your contacts. You don't type +1-555-0199 every time you call Mom; you just select "Mom".
Syntax and Usage
To create a type alias, we use the type keyword, followed by the name (PascalCase), an equals sign =, and the type definition.
// β
The Clean Solution
// 1. Define the shape once
type User = {
id: string;
name: string;
email: string;
isActive?: boolean; // Optional property
};
// 2. Reuse it everywhere
function registerUser(user: User) {
console.log("Registering " + user.name);
}
function deleteUser(user: User) {
// TypeScript knows 'user' has an 'id'
console.log("Deleting user ID: " + user.id);
}The Superpower of type: Primitives and Unions
Here is where type flexes its muscles. Unlike interfaces (which we will see in a moment), a type can represent anything, not just objects.
1. Primitive Aliases:
Sometimes you want to make your code more readable by aliasing simple types.
type UUID = string;
const currentId: UUID = "a1-b2-c3"; // It's just a string, but semantic.2. Union Types (Crucial Industry Standard):
This is the most common reason developers reach for type. You can define a value that can be one of several types.
type Status = "pending" | "approved" | "rejected";
type ID = string | number;
let userStatus: Status = "pending";
// userStatus = "completed"; // β Error! "completed" is not in the union.2. Key Differences Between Type Aliases and Interfaces
Now that we love type, why does interface even exist?
An Interface is a way to define a contract for the shape of an object. It cannot handle primitives (like string) or unions (like A | B) directly. It is strictly for object shapes.
Let's look at the syntax comparison:
// Type Alias
type Car = {
model: string;
year: number;
};
// Interface
interface Truck {
model: string;
year: number;
}They look almost identical, right? But here are the 3 technical differences you might be asked about in an interview.
Difference #1: Extending (Inheritance) π§¬
In Object Oriented Programming (OOP), we often want a base entity and a specific entity that "inherits" properties.
Interface uses extends:
Interfaces have a hierarchical syntax specifically for this.
interface Animal {
name: string;
}
interface Bear extends Animal {
honey: boolean;
}
const yogi: Bear = { name: "Yogi", honey: true };Type uses Intersection &:
Types don't "extend" in the strict sense; they combine via intersection.
type Animal = {
name: string;
};
type Bear = Animal & {
honey: boolean;
};
const winnie: Bear = { name: "Winnie", honey: true };Technical Note: While they achieve the same result usually, extends checks validity slightly better than intersection &. If you try to extend with a conflicting property (e.g., name is number in child but string in parent), interface throws an error immediately. & might create a never type.
Difference #2: Declaration Merging (The Magic Trick) π©
This is the distinct feature of interfaces. If you define an Interface twice, TypeScript automatically merges them. If you define a Type twice, TypeScript yells at you.
Interface Merging:
interface Window {
title: string;
}
interface Window {
tsVersion: string;
}
// Result: The Window interface now has BOTH properties.
const myWindow: Window = {
title: "My App",
tsVersion: "5.3"
};Why is this useful? This is how you add properties to existing libraries. If you install a library that puts a global variable on the window object, you can "augment" the global window interface to tell TypeScript about it.
Type Collision:
type Book = { pages: number };
type Book = { title: string };
// β Error: Duplicate identifier 'Book'.Difference #3: Scope of Capability π
- Interfaces can only describe objects or functions.
- Types can describe objects, functions, primitives, unions, tuples, and intersections.
If you need type ID = number | string, you cannot use an interface.
3. Best Practices: When to Choose 'type' over 'interface'
So, which one should you use?
Years ago, the TypeScript team recommended interface because it performed slightly better. Today, the performance difference is negligible.
Here is the modern industry standard heuristic:
1. Writing Applications? Prefer type π οΈ
If you are building a React, Vue, Node, or Angular app, consistency is key.
- Use
typefor your component props, state, and DTOs (Data Transfer Objects). - Why? Because you will inevitably need Union types (
string | null,Status, etc.). Usingtypefor everything keeps your syntax consistent (type = ...) rather than switching betweeninterfaceandtypedepending on whether you need a union or an object.
2. Writing Libraries? Prefer interface π¦
If you are publishing an NPM package for others to use (like axios or express):
- Use
interfacefor your public APIs. - Why? Because your users might need to extend your definitions or use Declaration Merging to patch your types if they find a bug or need to add custom properties to your objects.
3. Need Tuples or Unions? Use type β‘
You have no choice here.
// Tuple: An array with fixed types at fixed positions
type Coordinates = [number, number];
// Union
type Result = "Success" | "Failure";Summary Table
| Feature | Interface | Type Alias |
|---|---|---|
| Describes Objects | β | β |
| Describes Functions | β | β |
| Describes Unions / Tuples | β | β |
| Describes Primitives | β | β |
Use extends keyword |
β | β (Uses &) |
| Declaration Merging | β | β |
| Computed Properties | Limited | β |
π§ Fun Fact
The TypeScript compilation error messages for
interfacesare sometimes shorter and easier to read thantypesinvolving heavy intersections (&). However, in VS Code hover-previews,typeoften shows the full object shape immediately, whereasinterfacejust shows the name of the interface. Pick your poison!
Hands-on Challenge
Try converting this interface structure into a type structure using intersections (&):
interface Person {
name: string;
}
interface Employee extends Person {
salary: number;
}Hint: Remember how Bear was defined in the examples above!
π References & Further Reading
Challenge
You are building the type system for an e-commerce platform. Your task is to define a set of related types and interfaces to model products and orders, making sure to use the correct TypeScript keyword (type or interface) based on the specific requirements for each definition.
Requirements:
- Create a
typealias namedProductDimensionsthat represents a tuple containing exactly three numbers: length, width, and height. - Create a
typealias namedOrderStatusthat represents a union of the following string literals:"pending","shipped","delivered", and"cancelled". - Define a base
interfacenamedProduct. It should have anid(string),name(string), andprice(number). - Define an
interfacenamedDigitalProductthat inherits fromProductand adds adownloadUrlproperty (string). - Define an
interfacenamedPhysicalProductthat inherits fromProductand adds ashippingWeightproperty (number) and adimensionsproperty using theProductDimensionstype. - Using declaration merging, augment the original
Productinterface to include a new propertytags, which should be an array of strings. - Create a
typealias namedOrderableItemwhich must be a union type that can be either aDigitalProductor aPhysicalProduct. - Finally, create a
typealias for anOrder. This type should have anorderId(string), astatusproperty using theOrderStatustype, and anitemproperty using theOrderableItemtype.
Expected result
Your final code should correctly define a set of TypeScript type aliases and interfaces. The evaluation will check for the following definitions with the correct properties and relationships:
- A
typealiasProductDimensionsdefined as a tuple[number, number, number]. - A
typealiasOrderStatusdefined as a union"pending" | "shipped" | "delivered" | "cancelled". - An
interfaceProductthat, through two declarations, containsid: string,name: string,price: number, andtags: string[]. - An
interfaceDigitalProductthat uses theextendskeyword onProductand adds the propertydownloadUrl: string. - An
interfacePhysicalProductthat uses theextendskeyword onProductand adds the propertiesshippingWeight: numberanddimensions: ProductDimensions. - A
typealiasOrderableItemdefined as a unionDigitalProduct | PhysicalProduct. - A
typealiasOrderdefined as an object shape with propertiesorderId: string,status: OrderStatus, anditem: OrderableItem.