Learn TypeScript Β· 6/14

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:

typescript
// ❌ 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.

typescript
// βœ… 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.

typescript
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.

typescript
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:

typescript
// 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.

typescript
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.

typescript
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:

typescript
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:

typescript
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 type for your component props, state, and DTOs (Data Transfer Objects).
  • Why? Because you will inevitably need Union types (string | null, Status, etc.). Using type for everything keeps your syntax consistent (type = ...) rather than switching between interface and type depending 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 interface for 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.

typescript
// 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 interfaces are sometimes shorter and easier to read than types involving heavy intersections (&). However, in VS Code hover-previews, type often shows the full object shape immediately, whereas interface just shows the name of the interface. Pick your poison!


Hands-on Challenge

Try converting this interface structure into a type structure using intersections (&):

typescript
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:

  1. Create a type alias named ProductDimensions that represents a tuple containing exactly three numbers: length, width, and height.
  2. Create a type alias named OrderStatus that represents a union of the following string literals: "pending", "shipped", "delivered", and "cancelled".
  3. Define a base interface named Product. It should have an id (string), name (string), and price (number).
  4. Define an interface named DigitalProduct that inherits from Product and adds a downloadUrl property (string).
  5. Define an interface named PhysicalProduct that inherits from Product and adds a shippingWeight property (number) and a dimensions property using the ProductDimensions type.
  6. Using declaration merging, augment the original Product interface to include a new property tags, which should be an array of strings.
  7. Create a type alias named OrderableItem which must be a union type that can be either a DigitalProduct or a PhysicalProduct.
  8. Finally, create a type alias for an Order. This type should have an orderId (string), a status property using the OrderStatus type, and an item property using the OrderableItem type.

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:

  1. A type alias ProductDimensions defined as a tuple [number, number, number].
  2. A type alias OrderStatus defined as a union "pending" | "shipped" | "delivered" | "cancelled".
  3. An interface Product that, through two declarations, contains id: string, name: string, price: number, and tags: string[].
  4. An interface DigitalProduct that uses the extends keyword on Product and adds the property downloadUrl: string.
  5. An interface PhysicalProduct that uses the extends keyword on Product and adds the properties shippingWeight: number and dimensions: ProductDimensions.
  6. A type alias OrderableItem defined as a union DigitalProduct | PhysicalProduct.
  7. A type alias Order defined as an object shape with properties orderId: string, status: OrderStatus, and item: OrderableItem.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.