Interfaces or Type Aliases? Oh, my!

Prologue: Type unions and intersections

A | B is called a type union.

type StringOrNumber = string | number
var subject: StringOrNumber
subject = 'hello' // OK
subject = 2 // OK
subject = true // error

A & B is called a type intersection. It is mostly commonly used to merge object types .

type Person = { name: string }
type Callable = { phone: string }
type CallablePerson = Person & Callable
var person: CallablePerson = { name: 'John' } // error, missing "phone"

Interfaces or Type Aliases? Oh, my!

  • Which one to use? Whatever. Both declare types!

  • Type aliases can receive other things than objects; It can receive any declared type. Most noticeable exclusive to those are:

    • Type unions and intersections;

    • Conditional types;

  • Interfaces work exclusively with objects (functions are also objects!). Exclusive to interfaces are:

    • The OOPish extends clause, which is somewhat similar to the type union of two objects;

    • Declaration merging. When you declare 2 interfaces with the same name, instead of clashing, their properties will merge. (They can still clash if their properties are incompatible, of course);

    • Common use of declaration merging: Add another property to the global DOM's Window declaration.

Type alias sample below. Almost the same capabilities and syntax.

Last updated

Was this helpful?