Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

TypeScript Interface vs Type: Differences, Examples and When to Use Each

Both interface and type can describe an object in TypeScript, but they are not interchangeable in every situation. Interfaces can be reopened; aliases can name unions, tuples and computed types. The choice affects library contracts, domain models and compiler diagnostics. Each example is independent and can be checked with --strict.

Published Written by Reading time 9 min read
On this page Contents: quick navigation between sections

The basic difference: describing an object

interface User {
  readonly id: string;
  name: string;
  email?: string;
}

type UserData = {
  readonly id: string;
  name: string;
  email?: string;
};

const user: User = { id: "42", name: "Ada" };
const data: UserData = user;
const sameShape: User = data;
Capabilityinterfacetype
Object and function shapesYesYes
Unions and tuplesNoYes
Declaration mergingYesNo
Mapped typesNoYes
Runtime validationNoNo

Both declarations describe a required id and name and an optional email. TypeScript compares their structures rather than assigning a distinct identity to each name, so assignments work in both directions. [1][8]

readonly prevents writes through a typed reference but does not freeze a JavaScript object. Fresh object literals also receive excess property checks; neither declaration creates an exact runtime schema. [2]

What can type express that interface cannot?

type UserId = string;
type Point = readonly [number, number];
type Theme = "light" | "dark";
type FormatPrice = (value: number) => string;

interface Formatter {
  (value: number): string;
}

const format: FormatPrice = (value) => value.toFixed(2);
const formatter: Formatter = format;

An alias can name a primitive, a union of literals, a tuple or a computed type. An interface describes an object shape, including a callable object, so both forms can describe functions. [1][2]

type UserId = string is still a string and does not prevent accidental mixing with other string identifiers. Distinct identifiers need an additional typing strategy. Theme, in contrast, limits values to two literal alternatives.

Declaration merging

interface PluginOptions {
  enabled: boolean;
}

interface PluginOptions {
  timeoutMs: number;
}

const options: PluginOptions = {
  enabled: true,
  timeoutMs: 5000,
};

// @ts-expect-error: duplicate type alias
type Settings = { enabled: boolean };

// @ts-expect-error: duplicate type alias
type Settings = { timeoutMs: number };

Two interface declarations with the same name in the same scope can merge. Here both fields become required. Repeated non-function members must have compatible declarations; merging is not a way to replace their types. [3]

Aliases cannot merge. For public libraries, an open interface can be a deliberate extension point, but declaring fields that the implementation does not provide is unsafe. Module augmentation changes the type information, not executable behavior.

Extending types: extends versus intersections

type Base = { id: string };

interface Product extends Base {
  price: number;
}

type ProductData = Base & { price: number };

// @ts-expect-error: incompatible property override
interface Invalid extends Base {
  id: number;
}

type Conflict = Base & { id: number };

// @ts-expect-error: id is never
const invalid: Conflict = { id: "42" };

// Explicitly replace the property:
type NumericId = Omit<Base, "id"> & { id: number };

An interface can extend an object type alias with statically known members. An alias can combine object types using &. In the simple case their resulting structures match. [2]

Conflicts behave differently: extends rejects an incompatible override at the declaration, while an intersection of string and number makes id have type never. Intersection is not overriding. To intentionally replace a field, remove it with Omit and declare it again.

Generics and class contracts

interface Repository<T> {
  get(id: string): Promise<T | undefined>;
}

type Item = { id: string; name: string };
type Store<T> = { save(value: T): void };

class MemoryRepository implements Repository<Item>, Store<Item> {
  private items = new Map<string, Item>();

  async get(id: string): Promise<Item | undefined> {
    return this.items.get(id);
  }

  save(value: Item): void {
    this.items.set(value.id, value);
  }
}

Both interfaces and aliases accept generic parameters. Repository<T> models reading, and Store<T> models writing. A class can implement both because the alias has a statically known object shape. [5][6]

implements checks the instance contract; it does not generate methods, change their inferred types or supply an implementation. A class cannot directly implement a union of alternative object shapes. Design contracts around actual capabilities instead of artificial inheritance hierarchies.

Derived types: mapped and utility types

interface Profile {
  id: string;
  name: string;
  email: string;
}

type Editable = Pick<Profile, "name" | "email">;
type Patch = Partial<Editable>;

type FieldErrors<T> = {
  [K in keyof T]?: string;
};

const errors: FieldErrors<Editable> = {
  email: "Invalid email",
};

const patch: Patch = { name: "Ada" };

A form does not need a manually duplicated Profile. Pick selects editable fields, Partial makes them optional, and the mapped type FieldErrors assigns an error message type to each key. [7]

A mapped type can use an interface as its input; an alias is a natural way to name the result. Partial is shallow, so required members of nested objects remain required when the nested object is present.

Frontend state: discriminated unions

interface Product {
  id: string;
  name: string;
}

type LoadState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: Product[] }
  | { status: "error"; message: string };

function describe(state: LoadState): string {
  switch (state.status) {
    case "idle":
      return "Ready";

    case "loading":
      return "Loading";

    case "success":
      return `${state.data.length} items`;

    case "error":
      return state.message;

    default: {
      const exhaustive: never = state;

      return exhaustive;
    }
  }
}

Independent flags such as isLoading, hasError and optional data allow contradictory combinations. A union with a status discriminator ties fields to the appropriate state. After checking status, the compiler knows which properties are available. [4]

Assigning the remaining value to never in the default branch detects unhandled variants when the union grows. For domain models and request states, this is often preferable to a single object with many optional properties. The example combines a Product interface with a state alias.

API responses: typing is not validation

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

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "string" &&
    "name" in value &&
    typeof value.name === "string"
  );
}

function parseUser(json: string): User {
  const value: unknown = JSON.parse(json);

  if (!isUser(value)) {
    throw new Error("Invalid user");
  }

  return value;
}

parseUser('{"id":"42","name":"Ada"}');

Interfaces and aliases disappear when JavaScript is emitted. JSON.parse(text) as User does not check a server response and can conceal invalid data. [9]

Treat external data as unknown and validate required fields at the boundary. The example guard checks two string properties, not business constraints such as identifier format. Use schema validators for more complex payloads. Malformed JSON itself also throws an exception.

Compiler performance and team conventions

interface Config {
  mode: "light" | "dark";
  retries: number;
}

const config = {
  mode: "dark",
  retries: 3,
} satisfies Config;

const mode: "dark" = config.mode;

// @ts-expect-error: invalid literal
const broken = { mode: "auto", retries: 3 } satisfies Config;

TypeScript's performance guidance favors interface hierarchies over complex intersections in some cases, including because interface relationships can be cached. This does not make every alias slower. Measure the actual project using tsc --extendedDiagnostics with the same configuration. [10]

satisfies works with both kinds of type. It checks expression compatibility without replacing the expression's type with the target annotation; here the dark literal is retained. [11] Establish a consistent convention for plain objects while retaining aliases for unions and type transformations. Avoid mechanical rewrites of working declarations.

For ordinary object shapes, both forms are valid. Interfaces are especially useful for deliberately extensible contracts and object hierarchies, while aliases suit unions, tuples and derived types. A frontend model can combine an interface for data, a union for state and a mapped type for forms. Prioritize semantics and type safety over a universal keyword preference.

TypeScript Interface Type Alias Declaration Merging Intersection Types Union Types Generics Mapped Types Type Safety Frontend Architecture

Frequently asked questions

Is interface faster than type?

Not in the browser: both are erased from emitted JavaScript. Complex intersections can be more expensive during type checking. [9][10]

Can an interface extend a type alias?

Yes, if the alias denotes an object type or suitable intersection with statically known members. It cannot extend a union. [2]

Can a class implement a type alias?

Yes, if the alias describes a suitable object shape. A union of alternative shapes is not a valid implements target. [6]

Can a type alias be reopened?

No. Redeclaring the same alias in the same scope is an error; interfaces can merge. [1][3]

Do interface and type validate API responses?

No. Runtime checks such as a type guard or schema validator are required. [9]

Sources and references

  1. TypeScript Handbook: Everyday Types↩1↩2↩3↩4↩5
  2. TypeScript Handbook: Object Types↩1↩2↩3↩4↩5
  3. TypeScript Handbook: Declaration Merging↩1↩2↩3
  4. TypeScript Handbook: Narrowing↩
  5. TypeScript Handbook: Generics↩
  6. TypeScript Handbook: Classes↩1↩2
  7. TypeScript Handbook: Mapped Types↩1↩2
  8. TypeScript Handbook: Type Compatibility↩1↩2
  9. TypeScript Handbook: The Basics↩1↩2↩3↩4
  10. TypeScript Wiki: Performance↩1↩2
  11. TypeScript 4.9: The satisfies Operator↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning