How to Use Interfaces and Types in TypeScript

How to Use Interfaces and Types in TypeScript

A deep technical analysis of interfaces and type aliases in TypeScript. Learn compiler internals, performance implications, and enterprise patterns.

In large-scale enterprise codebases, choices surrounding type system ergonomics impact not only developer experience but also compiler performance, bundle boundaries, and maintainability across distributed teams.

TypeScript provides two primary constructs for defining structural shapes: interface and type (type aliases). While modern TypeScript versions have blurred the surface-level operational differences between them, treating them as interchangeable is a architectural mistake.

This guide explores the structural mechanics, compiler-level differences, performance trade-offs, and domain-modeling patterns for interface and type at enterprise scale.


1. The Underpinning Model: Structural Typing and Set Theory

To understand when to deploy interface versus type, you must first understand how TypeScript models types. TypeScript’s type system is structural, not nominal, and operates on Set Theory.

       Set Theory Equivalent in TypeScript
┌─────────────────────────────────────────────────┐
│              Unknown (Universal Set)            │
│  ┌───────────────────────────────────────────┐  │
│  │           Object / Record Types           │  │
│  │  ┌─────────────────┐ ┌─────────────────┐  │  │
│  │  │  Interface A    │ │   Type B        │  │  │
│  │  │  { id: string } │ │  { age: number }│  │  │
│  │  │        ┌────────┴─┴──────┐          │  │  │
│  │  │        │ Intersection    │          │  │  │
│  │  │        │  A & B / Extends│          │  │  │
│  │  │        └────────┬─┬──────┘          │  │  │
│  │  └─────────────────┘ └─────────────────┘  │  │
│  └───────────────────────────────────────────┘  │
│              Never (Empty Set ∅)                │
└─────────────────────────────────────────────────┘
  • Types as Sets: A type definition defines a set of allowed values. string is an infinite set of all textual sequences. { id: string } is the set of all objects containing at least an id property of type string.
  • Interfaces as Object Schema Contracts: An interface explicitly defines the shape of an object or class instance, acting as an extensible contract for named object structures.
  • Type Aliases as Identity Maps: A type alias creates a compile-time name binding to any valid type expression, including primitives, unions, intersections, tuples, and object literals.

2. Under the Hood: Compiler Mechanics and Performance

When operating in repositories with hundreds of thousands of lines of code, the choice between interface and type can directly impact local editing latency and build pipeline durations.

Symbol Resolution & Cache Invalidation

The TypeScript compiler (tsc) handles interface and type resolution using different internal data structures:

Interface Inheritance Path (Flat Object Cache)
┌────────────────┐      ┌────────────────┐
│  BaseInterface │ ---> │ DerivedInterface│  ===> Single Flat Type Representation
└────────────────┘      └────────────────┘       (Cached in memory via symbol ID)

Type Intersection Path (Deferred Evaluation Graph)
┌────────────────┐      ┌────────────────┐
│     Type A     │  &   │     Type B     │  ===> Computed Type Relationship Engine
└────────────────┘      └────────────────┘       (Evaluated recursively on every check)
  1. Interfaces Create Flat Object Types: When an interface extends another interface or defines properties, tsc builds a single flat object type structure and caches it by its symbol name. Detecting property conflicts across extended interfaces occurs during declaration merging or class implementation checks, allowing fast $O(1)$ property lookups.
  2. Type Intersections Are Evaluated Lazily: When you intersect types using type C = A & B, tsc creates an Intersection Type Engine. Instead of computing a single flat object shape immediately, tsc retains the constituent parts and recursively checks compatibility across the intersection structure when evaluating assignments.

Practical Impact on tsc Check Time

In extensive monorepos, overuse of complex object intersections (TypeA & TypeB & TypeC) can lead to exponential type-checking times ($O(n^2)$ complexity) because tsc re-checks deep relationships across intersections.

Key Rule for Large Codebases: Prefer interface extends over type intersections (&) for pure object-to-object structural relationships. Interfaces allow the compiler to cache relationships by shape, minimizing build times and memory consumption during type-checking.


3. Deep Dive: Interfaces (interface)

An interface is designed to model object-oriented structural shapes, contracts, and APIs.

Key Capabilities

1. Declaration Merging

Interfaces are open-ended. Multiple interface declarations sharing the same identifier within the same scope will merge their signatures automatically.

// Initial API definition inside a core module
interface AppConfig {
  env: 'development' | 'production' | 'staging';
  port: number;
}

// Module extension in a secondary plugin or application layer
interface AppConfig {
  tracingEnabled?: boolean;
  metricsPort?: number;
}

// Resulting runtime/compile-time contract requires all properties
const config: AppConfig = {
  env: 'production',
  port: 8080,
  tracingEnabled: true,
};

Enterprise Application: Declaration merging is required when building open SDKs, enterprise frameworks, or overriding third-party ambient declarations (e.g., adding custom properties to Express’s Request or Window’s global object).

// Extending ambient global types safely
declare global {
  namespace Express {
    interface Request {
      correlationId: string;
      userContext?: {
        tenantId: string;
        roles: string[];
      };
    }
  }
}

2. Clear Polymorphic Inheritance (extends)

When defining multi-tiered enterprise domain models, interface extends produces readable compiler errors and prevents incompatible field overrides at the point of declaration.

interface Entity {
  id: string;
  createdAt: Date;
  updatedAt: Date;
}

interface UserEntity extends Entity {
  email: string;
  // Compiler error caught immediately here if overridden incompatibly:
  // id: number; -> Error: Interface 'UserEntity' incorrectly extends interface 'Entity'.
}

4. Deep Dive: Type Aliases (type)

A type alias creates an alternative name for any valid TypeScript expression. Unlike interfaces, type aliases are closed and cannot be re-opened for declaration merging.

Key Capabilities

1. Union Types and Discriminated Unions

Types excel at defining domain state machines and non-object structural abstractions. You cannot declare a union directly using an interface.

export type PaymentStatus = 
  | { status: 'idle' }
  | { status: 'processing'; transactionId: string }
  | { status: 'succeeded'; receiptUrl: string; amount: number }
  | { status: 'failed'; errorCode: string; errorMessage: string };

export function processPaymentState(state: PaymentStatus): string {
  switch (state.status) {
    case 'idle':
      return 'Payment initialized.';
    case 'processing':
      return `Processing payment ID: ${state.transactionId}`;
    case 'succeeded':
      return `Receipt available at: ${state.receiptUrl}`;
    case 'failed':
      return `Error [${state.errorCode}]: ${state.errorMessage}`;
    default: {
      // Exhaustiveness checking guarantees all branch paths are modeled
      const _exhaustiveCheck: never = state;
      return _exhaustiveCheck;
    }
  }
}

2. Branded Types (Nominal Emulation)

Since TypeScript uses structural subtyping, primitive types like string can be accidentally substituted (e.g., passing a UserId where an OrderId is expected). You can construct branded types using type aliases:

declare const BrandSymbol: unique symbol;

export type Brand<T, K extends string> = T & {
  readonly [BrandSymbol]: K;
};

export type UserId = Brand<string, 'UserId'>;
export type OrderId = Brand<string, 'OrderId'>;

// Factory / Type-Guard Functions
export function makeUserId(id: string): UserId {
  return id as UserId;
}

export function makeOrderId(id: string): OrderId {
  return id as OrderId;
}

function processOrder(userId: UserId, orderId: OrderId) {
  // Business logic here
}

const myUser = makeUserId('usr_123');
const myOrder = makeOrderId('ord_999');

// processOrder(myOrder, myUser); 
// ❌ Type Error: Type 'Brand<string, "OrderId">' is not assignable to type 'UserId'

3. Advanced Mapped Types, Dynamic Keys, and Utility Types

Type aliases are required for non-trivial type manipulations, mapped types, conditional logic, and template literals.

// Convert all methods of an interface into async signatures dynamically
export type Promisify<T> = {
  [K in keyof T]: T[K] extends (...args: infer A) => infer R
    ? (...args: A) => Promise<R>
    : T[K];
};

// Event Handler Naming with Template Literals
type EntityEvent = 'created' | 'updated' | 'deleted';
type ModelName = 'User' | 'Order' | 'Invoice';

export type EventHookName = `on${ModelName}${Capitalize<EntityEvent>}`;
// Evaluates to: "onUserCreated" | "onUserUpdated" | "onUserDeleted" | "onOrderCreated" ...

5. Structural Comparison: Interface vs Type

To systematically select the appropriate construct, consider the following structural and operational differences:

Capability / Feature interface type
Primary Intent Structural object shapes and OOP class contracts. Type expressions, unions, primitives, mapped types.
Declaration Merging ✅ Supported. Open for augmentation across files. ❌ Not supported. Identity is closed.
Extensibility Syntax interface B extends A Intersections: type B = A & { ... }
Compiler Performance High ($O(1)$ symbol lookup, relationship caching). Moderate-to-Low on high nested intersections.
Primitives / Unions / Tuples ❌ Cannot model directly. ✅ Native support (type ID = string | number).
Mapped / Conditional Types ❌ Not supported directly inside interface body. ✅ Supported.
implements for Classes Fully supported (predictable error messages). Supported only if shape resolves to a static object type.
Tooling & Error Messages Clear, named symbol paths in IDE tooltips. Flattens or prints full intersected types in errors.

6. Real-World Architectural Patterns

Here is how these theoretical rules translate to actual enterprise architecture patterns.

Pattern A: Clean Domain Entities (Hexagonal / Clean Architecture)

When building core domain entities, use Interfaces for public properties and dynamic functionality, combined with Branded Type Aliases for robust identifier checking.

// domain/types/common.ts
export type EntityId<TDomain extends string> = Brand<string, TDomain>;
export type Timestamp = Brand<number, 'Timestamp'>;

// domain/entities/user.ts
export interface UserProps {
  readonly id: EntityId<'User'>;
  readonly email: string;
  readonly role: 'admin' | 'member' | 'guest';
  readonly createdAt: Timestamp;
}

export interface IUserAggregate {
  readonly props: UserProps;
  canAccessResource(resourceId: string): boolean;
  updateEmail(newEmail: string): IUserAggregate;
}

export class UserAggregate implements IUserAggregate {
  constructor(public readonly props: UserProps) {}

  public canAccessResource(resourceId: string): boolean {
    return this.props.role === 'admin';
  }

  public updateEmail(newEmail: string): IUserAggregate {
    return new UserAggregate({
      ...this.props,
      email: newEmail,
    });
  }
}

Pattern B: Event-Driven Architecture (CQRS / Event Sourcing)

When constructing typed messaging boundaries, use Type Aliases for messages, combined with Discriminated Unions for strict payload safety.

// infrastructure/messaging/events.ts
export type DomainEvent<
  TType extends string,
  TPayload extends Record<string, unknown>
> = Readonly<{
  eventId: string;
  eventType: TType;
  timestamp: number;
  payload: TPayload;
}>;

export type UserCreatedEvent = DomainEvent<'USER_CREATED', {
  userId: EntityId<'User'>;
  email: string;
}>;

export type OrderPlacedEvent = DomainEvent<'ORDER_PLACED', {
  orderId: EntityId<'Order'>;
  userId: EntityId<'User'>;
  totalAmount: number;
}>;

// Aggregate Event Store Type Expression
export type ApplicationDomainEvent = 
  | UserCreatedEvent 
  | OrderPlacedEvent;

// Typed Event Router Handler
export type EventHandler<TEvent extends ApplicationDomainEvent> = (
  event: TEvent
) => Promise<void>;

7. Enterprise Engineering Decision Framework

To achieve consistency across engineering teams, adopt the following explicit rules within your organization’s TypeScript style guide or ESLint/Biome rulesets.

                  Designing a TypeScript Structure
                               │
                Is it an Object Shape / Class Contract?
                               │
                   ┌───────────┴───────────┐
                   YES                     NO
                   │                       │
      Is Declaration Merging Needed?   Use TYPE ALIAS
                   │                   (Unions, Primitives,
          ┌────────┴────────┐          Tuples, Functions)
          YES               NO
          │                 │
    Use INTERFACE     Use INTERFACE
    (Public SDKs /    (Standard Domain Shapes,
     Global Types)     Entity Models)

Mandate Rules summary

  1. Mandate interface for:

    • Public-facing API surface contracts and SDK shapes.
    • Object shapes intended for extension by consuming applications.
    • Class definitions using implements.
    • Standard domain models/entities that express object structural contracts.
  2. Mandate type for:

    • Union or intersection definitions (type Status = 'active' | 'inactive').
    • Primitive aliases and branded types (type Quantity = number).
    • Tuples, mapped types, conditional types, and complex utility transformations.
    • Function payload definitions and inline callbacks.
  3. Avoid Anti-Patterns:

    • Do not use intersection chaining for objects. Replace type C = A & B with interface C extends A, B to prevent evaluation penalties in tsc.
    • Do not wrap single primitives inside interfaces. Replace interface Id { val: string } with branded primitive types.
    • Do not export loose object literals as types when they represent class states. Reserve interface for structural object instances.

8. Automated Governance Strategy

Enforce these conventions across your engineering organization via static analysis tools:

ESLint Configuration (@typescript-eslint)

{
  "rules": {
    "@typescript-eslint/consistent-type-definitions": ["error", "interface"],
    "@typescript-eslint/no-type-alias": [
      "error",
      {
        "allowAliases": "in-unions-and-intersections",
        "allowCallbacks": "always",
        "allowLiterals": "in-signatures",
        "allowMappedTypes": "always"
      }
    ]
  }
}

By leveraging interface for structural object modeling and reserving type for type transformations, unions, and primitives, enterprise engineering teams can build scalable codebases that deliver predictable compile-time guarantees and consistent IDE performance.