[typescript] TypeScript: Interfaces vs Types

What is the difference between these statements (interface vs type)?

interface X {
    a: number
    b: string
}

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

This question is related to typescript

The answer is


the documentation has explained

  • One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.in older versions of TypeScript, type aliases couldn’t be extended or implemented from (nor could they extend/implement other types). As of version 2.7, type aliases can be extended by creating a new intersection type
  • On the other hand, if you can’t express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go.

Interfaces vs. Type Aliases


Interfaces vs types

Interfaces and types are used to describe the types of objects and primitives. Both interfaces and types can often be used interchangeably and often provide similar functionality. Usually it is the choice of the programmer to pick their own preference.

However, interfaces can only describe objects and classes that create these objects. Therefore types must be used in order to describe primitives like strings and numbers.

Here is an example of 2 differences between interfaces and types:

// 1. Declaration merging (interface only)

// This is an extern dependency which we import an object of
interface externDependency { x: number, y: number; }
// When we import it, we might want to extend the interface, e.g. z:number
// We can use declaration merging to define the interface multiple times
// The declarations will be merged and become a single interface
interface externDependency { z: number; }
const dependency: externDependency = {x:1, y:2, z:3}

// 2. union types with primitives (type only)

type foo = {x:number}
type bar = { y: number }
type baz = string | boolean;

type foobarbaz = foo | bar | baz; // either foo, bar, or baz type

// instances of type foobarbaz can be objects (foo, bar) or primitives (baz)
const instance1: foobarbaz = {y:1} 
const instance2: foobarbaz = {x:1} 
const instance3: foobarbaz = true 


When to use type?


Generic Transformations

Use the type when you are transforming multiple types into a single generic type.

Example:

type Nullable<T> = T | null | undefined
type NonNull<T> = T extends (null | undefined) ? never : T

Type Aliasing

We can use the type for creating the aliases for long or complicated types that are hard to read as well as inconvenient to type again and again.

Example:

type Primitive = number | string | boolean | null | undefined

Creating an alias like this makes the code more concise and readable.


Type Capturing

Use the type to capture the type of an object when the type is unknown.

Example:

const orange = { color: "Orange", vitamin: "C"}
type Fruit = typeof orange
let apple: Fruit

Here, we get the unknown type of orange, call it a Fruit and then use the Fruit to create a new type-safe object apple.


When to use interface?


Polymorphism

An interface is a contract to implement a shape of the data. Use the interface to make it clear that it is intended to be implemented and used as a contract about how the object will be used.

Example:

interface Bird {
    size: number
    fly(): void
    sleep(): void
}

class Hummingbird implements Bird { ... }
class Bellbird implements Bird { ... }

Though you can use the type to achieve this, the Typescript is seen more as an object oriented language and the interface has a special place in object oriented languages. It's easier to read the code with interface when you are working in a team environment or contributing to the open source community. It's easy on the new programmers coming from the other object oriented languages too.

The official Typescript documentation also says:

... we recommend using an interface over a type alias when possible.

This also suggests that the type is more intended for creating type aliases than creating the types themselves.


Declaration Merging

You can use the declaration merging feature of the interface for adding new properties and methods to an already declared interface. This is useful for the ambient type declarations of third party libraries. When some declarations are missing for a third party library, you can declare the interface again with the same name and add new properties and methods.

Example:

We can extend the above Bird interface to include new declarations.

interface Bird {
    color: string
    eat(): void
}

That's it! It's easier to remember when to use what than getting lost in subtle differences between the two.


When it comes to compilation speed, composed interfaces perform better than type intersections:

[...] interfaces create a single flat object type that detects property conflicts. This is in contrast with intersection types, where every constituent is checked before checking against the effective type. Type relationships between interfaces are also cached, as opposed to intersection types.

Source: https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections


Here's another difference. I will... buy you a beer if you can explain the reasoning or reason as to this state of affairs:

enum Foo { a = 'a', b = 'b' }

type TFoo = {
  [k in Foo]: boolean;
}

const foo1: TFoo = { a: true, b: false} // good
// const foo2: TFoo = { a: true }       // bad: missing b
// const foo3: TFoo = { a: true, b: 0}  // bad: b is not a boolean

// So type does roughly what I'd expect and want

interface IFoo {
//  [k in Foo]: boolean;
/*
  Uncommenting the above line gives the following errors:
  A computed property name in an interface must refer to an expression whose type is a      
    literal type or a 'unique symbol' type.
  A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
  Cannot find name 'k'.
*/
}

// ???

This sort of makes me want to say the hell with interfaces unless I'm intentionally implementing some OOP design pattern, or require merging as described above (which I'd never do unless I had a very good reason for it).


2019 Update


The current answers and the official documentation are outdated. And for those new to TypeScript, the terminology used isn't clear without examples. Below is a list of up-to-date differences.

1. Objects / Functions

Both can be used to describe the shape of an object or a function signature. But the syntax differs.

Interface

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

interface SetPoint {
  (x: number, y: number): void;
}

Type alias

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

type SetPoint = (x: number, y: number) => void;

2. Other Types

Unlike an interface, the type alias can also be used for other types such as primitives, unions, and tuples.

// primitive
type Name = string;

// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };

// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];

3. Extend

Both can be extended, but again, the syntax differs. Additionally, note that an interface and type alias are not mutually exclusive. An interface can extend a type alias, and vice versa.

Interface extends interface

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

Type alias extends type alias

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

Interface extends type alias

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

Type alias extends interface

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

4. Implements

A class can implement an interface or type alias, both in the same exact way. Note however that a class and interface are considered static blueprints. Therefore, they can not implement / extend a type alias that names a union type.

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

class SomePoint implements Point {
  x = 1;
  y = 2;
}

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

class SomePoint2 implements Point2 {
  x = 1;
  y = 2;
}

type PartialPoint = { x: number; } | { y: number; };

// FIXME: can not implement a union type
class SomePartialPoint implements PartialPoint {
  x = 1;
  y = 2;
}

5. Declaration merging

Unlike a type alias, an interface can be defined multiple times, and will be treated as a single interface (with members of all declarations being merged).

// These two declarations become:
// interface Point { x: number; y: number; }
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };

https://www.typescriptlang.org/docs/handbook/advanced-types.html

One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.


Other answers are great! Few other things which Type can do but Interface can't

You can use union in type

type Name = string | { FullName: string };

const myName = "Jon"; // works fine

const myFullName: Name = {
  FullName: "Jon Doe", //also works fine
};

Iterating over union properties in type

type Keys = "firstName" | "lastName";

type Name = {
  [key in Keys]: string;
};

const myName: Name = {
  firstName: "jon",
  lastName: "doe",
};

Intersection in type ( however, also supported in Interface with extends)

type Name = {
  firstName: string;
  lastName: string;
};

type Address = {
  city: string;
};

const person: Name & Address = {
  firstName: "jon",
  lastName: "doe",
  city: "scranton",
};

Also not that type was introduced later as compared to interface and according to the latest release of TS type can do *almost everything which interface can and much more!


*except Declaration merging (personal opinion: It's good that it's not supported in type as it may lead to inconsistency in code)


Typescript handbook gives the answer: the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.

Link: https://www.typescriptlang.org/docs/handbook/advanced-types.html#interfaces-vs-type-aliases


As of TypeScript 3.2 (Nov 2018), the following is true:

enter image description here


There is also a difference in indexing.

interface MyInterface {
  foobar: string;
}

type MyType = {
  foobar: string;
}

const exampleInterface: MyInterface = { foobar: 'hello world' };
const exampleType: MyType = { foobar: 'hello world' };

let record: Record<string, string> = {};

record = exampleType;      // Compiles
record = exampleInterface; // Index signature is missing

So please consider this example, if you want to index your object

Take a look on this question


Examples with Types:

// create a tree structure for an object. You can't do the same with interface because of lack of intersection (&)

type Tree<T> = T & { parent: Tree<T> };

// type to restrict a variable to assign only a few values. Interfaces don't have union (|)

type Choise = "A" | "B" | "C";

// thanks to types, you can declare NonNullable type thanks to a conditional mechanism.

type NonNullable<T> = T extends null | undefined ? never : T;

Examples with Interface:

// you can use interface for OOP and use 'implements' to define object/class skeleton

interface IUser {
    user: string;
    password: string;
    login: (user: string, password: string) => boolean;
}

class User implements IUser {
    user = "user1"
    password = "password1"

    login(user: string, password: string) {
        return (user == user && password == password)
    }
}

// you can extend interfaces with other interfaces

    interface IMyObject {
        label: string,
    }

    interface IMyObjectWithSize extends IMyObject{
        size?: number
    }

Well 'typescriptlang' seems to be recommending using interface over types where ever possible. @typescriptlang Interface vs Type Alias


In addition to the brilliant answers already provided, there are noticeable differences when it comes to extending types vs interfaces. I recently run into a couple of cases where an interface can't do the job:

  1. Cannot extend a union type using an interface
  2. Cannot extend generic interface

TLDR;

My personal convention, which I describe below, is this:

Always prefer interface over type.

When to use type:

  • Use type when defining an alias for primitive types (string, boolean, number, bigint, symbol, etc)
  • Use type when defining tuple types
  • Use type when defining function types
  • Use type when defining a union
  • Use type when trying to overload functions in object types via composition
  • Use type when needing to take advantage of mapped types

When to use interface:

  • Use interface for all object types where using type is not required (see above)
  • Use interface when you want to take advatange of declaration merging.

Primitive types

The easiest difference to see between type and interface is that only type can be used to alias a primitive:

type Nullish = null | undefined;
type Fruit = 'apple' | 'pear' | 'orange';
type Num = number | bigint;

None of these examples are possible to achieve with interfaces.

When providing a type alias for a primitive value, use the type keyword.

Tuple types

Tuples can only be typed via the type keyword:

type row = [colOne: number, colTwo: string];

Use the type keyword when providing types for tuples.

Function types

Functions can be typed by both the type and interface keywords:

// via type
type Sum = (x: number, y: number) => number;

// via interface
interface Sum {
  (x: number, y: number): number;
}

Since the same effect can be achieved either way, the rule will be to use type in these scenarios since it's a little easier to read (and less verbose).

Use type when defining function types.

Union types

Union types can only be achieved with the type keyword:

type Fruit = 'apple' | 'pear' | 'orange';
type Vegetable = 'broccoli' | 'carrot' | 'lettuce';

// 'apple' | 'pear' | 'orange' | 'broccoli' | 'carrot' | 'lettuce';
type HealthyFoods = Fruit | Vegetable;

When defining union types, use the type keyword

Object types

An object in javascript is a key/value map, and an "object type" is typescript's way of typing those key/value maps. Both interface and type can be used when providing types for an object as the original question makes clear. So when do you use type vs interface for object types?

Intersection vs Inheritance

With types and composition, I can do something like this:

type NumLogger = { 
  log: (val: number) => void;
}
type StrAndNumLogger = NumLogger & { 
  log: (val: string) => void;
}

const logger: StrAndNumLogger = {
  log: (val: string | number) => console.log(val)
}

logger.log(1)
logger.log('hi')

Typescript is totally happy. What about if I tried that with interfaces:

interface NumLogger { 
    log: (val: number) => void;
}
interface StrAndNumLogger extends NumLogger { 
    log: (val: string) => void; 
};

The declaration of StrAndNumLogger gives me an error:

With interfaces, the subtypes have to exactly match the types declared in the super type, otherwise TS will throw an error like the one above.

When trying to overload functions in object types, you'll be better off using the type keyword.

Declaration Merging

The key aspect to interfaces in typescript that distinguish them from types is that they can be extended with new functionality after they've already been declared. A common use case for this feature occurs when you want to extend the types that are exported from a node module. For example, @types/jest exports types that can be used when working with the jest library. However, jest also allows for extending the main jest type with new functions. For example, I can add a custom test like this:

jest.timedTest = async (testName, wrappedTest, timeout) =>
  test(
    testName,
    async () => {
      const start = Date.now();
      await wrappedTest(mockTrack);
      const end = Date.now();

      console.log(`elapsed time in ms: ${end - start}`);
    },
    timeout
  );

And then I can use it like this:

test.timedTest('this is my custom test', () => {
  expect(true).toBe(true);
});

And now the time elapsed for that test will be printed to the console once the test is complete. Great! There's only one problem - typescript has no clue that i've added a timedTest function, so it'll throw an error in the editor (the code will run fine, but TS will be angry).

To resolve this, I need to tell TS that there's a new type on top of the existing types that are already available from jest. To do that, I can do this:

declare namespace jest {
  interface It {
    timedTest: (name: string, fn: (mockTrack: Mock) => any, timeout?: number) => void;
  }
}

Because of how interfaces work, this type declaration will be merged with the type declarations exported from @types/jest. So I didn't just re-declare jest.It; I extended jest.It with a new function so that TS is now aware of my custom test function.

This type of thing is not possible with the type keyword. If @types/jest had declared their types with the type keyword, I wouldn't have been able to extend those types with my own custom types, and therefore there would have been no good way to make TS happy about my new function. This process that is unique to the interface keyword is called declaration merging.

Declaration merging is also possible to do locally like this:

interface Person {
  name: string;
}

interface Person {
  age: number;
}

// no error
const person: Person = {
  name: 'Mark',
  age: 25
};

If I did the exact same thing above with the type keyword, I would have gotten an error since types cannot be re-declared/merged. In the real world, javascript objects are much like this interface example; they can be dynamically updated with new fields at runtime.

Because interface declarations can be merged, interfaces more accurately represent the dynamic nature of javascript objects than types do, and they should be preferred for that reason.

Mapped object types

With the type keyword, I can take advantage of mapped types like this:

type Fruit = 'apple' | 'orange' | 'banana';

type FruitCount = {
  [key in Fruit]: number;
}

const fruits: FruitCount = {
  apple: 2,
  orange: 3,
  banana: 4
};

This cannot be done with interfaces:

type Fruit = 'apple' | 'orange' | 'banana';

// ERROR: 
interface FruitCount {
  [key in Fruit]: number;
}

When needing to take advantage of mapped types, use the type keyword