Interfaces & Types

In JavaScript, understanding how to work with types and interfaces is key to writing clear, maintainable code, especially when using TypeScript or JSDoc annotations. While JavaScript itself is dynamically typed, TypeScript introduces static typing features including interfaces and types.

Illustration of Interfaces & Types
Illustration of Interfaces & Types

💡 What Are Types?

Types define the shape and kind of data a variable can hold, such as string, number, or complex objects.

💡 What Are Interfaces?

Interfaces describe the structure that an object should have, specifying properties and their types. They act as contracts for objects.

Types vs Interfaces: Key Differences

Comparison of Types and Interfaces
FeatureTypeInterface
Can describe primitives, unions, tuplesYesNo
Can be extended (merged)Yes (via intersection)Yes (declaration merging)
Used to define object shapeYesYes
Can describe function signaturesYesYes
Declaration merging possibleNoYes

Defining an Interface

Interfaces specify object properties and types explicitly:

📌 Deep Dive: Interface Example

JAVASCRIPT (TypeScript)
interface Person {
  name: string;
  age: number;
  greet(): void;
}

const user: Person = {
  name: "Alice",
  age: 30,
  greet() {
    console.log("Hello!");
  }
};

Defining a Type Alias

Type aliases can define object shapes but also unions, primitives, and tuples:

📌 Deep Dive: Type Alias Example

JAVASCRIPT (TypeScript)
type Point = {
  x: number;
  y: number;
};

type ID = string | number; // union type

const p: Point = { x: 10, y: 20 };
const userId: ID = "abc123";

⚠️ Use Interfaces for Object Shapes

Prefer interfaces when defining object shapes, as they are extendable and support declaration merging, which is useful in larger codebases.

Extending Interfaces and Types

Both interfaces and types can be combined to create new types.

📌 Deep Dive: Extending

JAVASCRIPT (TypeScript)
// Interface extension
interface Animal {
  name: string;
}

interface Dog extends Animal {
  breed: string;
}

const myDog: Dog = { name: "Buddy", breed: "Golden Retriever" };

// Type intersection
type Cat = {
  name: string;
};

type CatInfo = Cat & { age: number };

const myCat: CatInfo = { name: "Whiskers", age: 3 };

💡 Interfaces Can Merge

Multiple interface declarations with the same name are merged automatically by TypeScript, enabling flexible extension.

Summary

  • Types are versatile aliases for any type, including primitives and unions.
  • Interfaces are primarily for describing object shapes and support merging.
  • Use interfaces for defining object contracts and types for other abstractions.
  • Both support extension—interfaces via extends, types via intersection (&).