codez.guru

What is a Type Alias?

A type alias gives a name to any type:

type UserID = string;
type Status = "active" | "inactive";

type Product = {
  id: number;
  name: string;
};

You can use type for primitives, unions, intersections, and functions.


What is an Interface?

An interface describes the structure of an object:

interface User {
  id: number;
  name: string;
}

Interfaces are extendable and composable, ideal for object shapes and class contracts.


Key Differences

Feature type interface
Objects
Primitives, unions, etc. ✅ (strings, unions, functions) ❌ only objects
Extendable ✅ via intersections (&) ✅ via extends
Declaration merging ❌ no ✅ supported
Better for classes ❌ not ideal ✅ recommended

When to Use type vs interface

Use interface when:

  • Defining object structures
  • Building APIs, classes, or data models
  • You benefit from declaration merging

Use type when:

  • Creating unions, tuples, or function signatures
  • Combining multiple types with | or &
  • Aliasing a primitive or non-object structure

Can You Combine Them?

Yes — you can use both together:

interface Person {
  name: string;
}

type WithAge = Person & { age: number };

> You can even use a type inside an interface or vice versa.


Summary

  • type is more flexible — can alias anything
  • interface is better for structured, extendable object types
  • Use interface for long-lived objects and APIs
  • Use type for complex unions, intersections, and primitives

Next up: Working with Enums — the right way to create named constants and semantic values.