Menu

Type Aliases and Interfaces

Lesson 2: Type Aliases and Interfaces

What are type aliases and interfaces?

Both give a name to a type so you can reuse it.

Feature type alias interface
Describe objects Yes Yes
Describe unions, tuples, primitives Yes (`type Id = string number`)
Extend another type & intersection extends keyword
Merge declarations with the same name No (error) Yes (declaration merging)
Error messages for large hierarchies Good Often clearer

Example

// Type aliases
type ProductId = string;
type Money = number; // in paise

type Product = {
  id: ProductId;
  name: string;
  price: Money;
  category: 'fruits' | 'dairy' | 'grains' | 'snacks';
};

// Interfaces
interface Customer {
  id: string;
  name: string;
  email: string;
}

interface PrimeCustomer extends Customer {
  membershipEndsOn: Date;
  freeDelivery: true;
}

// Extending a type alias with an intersection
type DiscountedProduct = Product & { discountPercent: number };

const riya: PrimeCustomer = {
  id: 'c7',
  name: 'Riya M',
  email: '[email protected]',
  membershipEndsOn: new Date('2027-03-31'),
  freeDelivery: true,
};

How it works

  • extends copies every property of Customer into PrimeCustomer and adds new ones.
  • & combines two types into one that has all properties of both (Module 5 covers intersections).
  • Declaration merging: two interface Window { ... } declarations combine into one. This is useful for adding properties to library types, but surprising if done by accident.

Which to choose? Pick one style for object shapes and stay consistent. A common convention:

Use For
interface Object shapes, especially public APIs and classes
type Unions, tuples, function types, mapped and conditional types

Common mistakes

Mistake Effect Fix
Trying to write a union with interface Syntax error Use type
Two interfaces with the same name by accident They silently merge Use unique names, or type for local shapes
Prefixing interfaces with I (IProduct) Outdated convention, noisy Use plain names: Product

Key takeaways

  • type and interface both name object shapes; type can also name unions and other types.
  • Use extends or & to build bigger types from smaller ones.

Try it: Create Product, CartItem (a product plus quantity), and Cart (an array of items plus couponCode?) using both styles.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details