HiveBrain v1.2.0
Get Started
← Back to all entries
principletypescriptCritical

Interfaces vs Types in TypeScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescripttypesinterfaces

Problem

What is the difference between these statements (interface vs type) in TypeScript?
interface X {
a: number
b: string
}

type X = {
a: number
b: string
};

Solution

Update March 2021: The newer TypeScript Handbook (also mentioned in nju-clc
answer below) has a section Interfaces vs. Type Aliases which explains the differences.

Original Answer (2016)

As per the (now archived) TypeScript Language Specification:

Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.

The specification goes on to mention:

Interface types have many similarities to type aliases for object type
literals, but since interface types offer more capabilities they are
generally preferred to type aliases. For example, the interface type

interface Point {
    x: number;
    y: number;
}


could be written as the type alias

type Point = {
    x: number;
    y: number;
};


However, doing so means the following capabilities are lost:

  • An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot No longer true since TS 2.7.



  • An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

Code Snippets

interface Point {
    x: number;
    y: number;
}
type Point = {
    x: number;
    y: number;
};

Context

Stack Overflow Q#37233735, score: 1336

Revisions (0)

No revisions yet.