155

What are the differences between the following?

type Foo = { 
    foo: string 
};
interface Foo {
   foo: string;
}
martiansnoop
  • 2,316
  • 2
  • 16
  • 16
  • 4
    type cannot be extended like interface extension. types are just aliases for a type. – PSL Apr 22 '16 at 01:03
  • 4
    Guidance available here : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html#type-alias – basarat Apr 22 '16 at 01:23
  • 2
    I mostly use type for external data, for example from a JSON file, or if you are only writing functions without using OOP classes. – Kokodoko Aug 16 '17 at 10:32
  • 1
    I found this article useful that explains the differences - https://medium.com/@martin_hotell/interface-vs-type-alias-in-typescript-2-7-2a8f1777af4c – Sandeep G B Oct 02 '18 at 20:11
  • 1
    The accepted answer is out-of-date. Updated explanation posted here (since that thread seems to be favored by Google): https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types/52682220#52682220 – jabacchetta Oct 06 '18 at 18:56
  • 1
    Possible duplicate of [Typescript: Interfaces vs Types](https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types) – Michael Freidgeim Oct 14 '19 at 21:03
  • for anyone interested to dig further https://adropincalm.com/blog/type-is-the-ultimate-type-eclipses-everything/ – borracciaBlu Jun 28 '23 at 22:53

6 Answers6

168

Interfaces can be extended

interface A {
  x: number;
}
interface B extends A {
  y: string;
}

and also augmented

interface C {
  m: boolean;
}
// ... later ...
interface C {
  n: number;
}

Type aliases, however, can represent some things interfaces can't

type NumOrStr = number | string;
type NeatAndCool = Neat & Cool;
type JustSomeOtherName = SomeType;

So in general if you just have a plain object type, as shown in your question, an interface is usually a better approach. If you find yourself wanting to write something that can't be written as an interface, or want to just give something a different name, a type alias is better.

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • 3
    `Type aliases, however, can represent some things interfaces can't` It seems to me your examples `NeatAndCool` and `JustSomeOtherName` can be created as interface that extend the existing `Neat`, `Cool` or `SomeType` types. – Rudey Oct 03 '17 at 06:54
  • Indeed the second and third examples can be created with an interface: `interface NeatAndCool extends Neat, Cool {}` `interface JustSomeOtherName extends SomeType {}` – peterjwest May 12 '18 at 21:13
  • 3
    Extending two interfaces will not always produce the same result as an intersection type, and not all types can be extended (whereas all types can be aliased or put into unions/intersections) – Ryan Cavanaugh May 13 '18 at 05:07
  • 1
    So what is the advantage of type? Can we say when we have interface, the type is not useful? – Mostafa Saadatnia May 05 '20 at 12:58
10

Putting things in perspective

let myAge = 25;
let totalStatesInMyCountry = 25

Look both the variables are equal, that is (myAge === totalStatesInMyCountry) but their context is totally different.

This is similar case for typescript's types and interfaces. Look for Foo

type Foo = {
    text: string
};
interface Foo {
    text: string;
}

Foo as a type and as an interface looks same, similar to (myAge === totalStatesInMyCountry), but this is just special case. Their context is totally different.

When to think about interface instead of types?

  1. You are enforcing that this class must have these methods. You are thinking about interfaces not types.

  2. You want to create multiple implementation of same contract. Like for contract toHumanReadableNumber(number) different implementations needed are 100000 -> 100,000, 100000 -> 100K and 100000 -> 100 Thousands. Lets say you are solving this problem by creating different classes for each requirement. You are thinking about classes and interfaces and not classes and types

  3. Interfaces are there to make system loosely coupled like implementing SOLID principles.

  4. Interfaces are substitute to multiple inheritances. A class can only inherit from single class, but can have multiple interfaces.

  5. For a class Point{ x:number,y:number, distanceFromCenter():number} , in context of interfaces, only distanceFromCenter():number matters.

----------x----------

Old Answer (before 31st Dec 2022)

Differences between these too are already in this thread.

type Foo = {
    foo: string
};
interface Foo {
    foo: string;
}

Here type Foo andinterface Foo looks almost similar so its confusing.

interface is contract that the following properties (herefoo:string) should be there in a object. interface is not class. It is used when language does not support Multiple Inheritance. So interface can be a common structure between different classes.

class Bar implements Foo {
    foo: string;
}

let p: Foo = { foo: 'a string' };

Buttype and interface are used in very different context.

let foo: Foo;
let today: Date = new Date();

Here type of foo is Foo and today is Date. Its like a variable decleration which holds the information of typeof other variable. type is like a superset of interfaces, classes, function signature, other types or even values (like type mood = 'Good' | 'Bad'). At the end type describes the possible structure or value of a variable.

amitdigga
  • 6,550
  • 4
  • 26
  • 31
6

It is wrong to say "Interfaces can be implemented" since types can also be implemented

type A = { a: string };


class Test implements A {

    a: string;
}

Although you can do this, you can't implement a type that is a Union of types, which makes totally sense honestly :)

Dan
  • 61
  • 1
  • 1
3

Types is kinda like Interfaces and vice versa: both can implemented by a class. but there are some important differences: 1. when Type is implemented by a class, the properties which belong to the Type must be initialized inside the class, whereas with Interface they must be declared. 2. as @ryan mentioned : Interface can extend another Interface. Types cannot.

type Person = {
    name:string;
    age:number;
}

// must initialize all props - unlike interface
class Manager implements Person {
    name: string = 'John';
    age: number = 55;

    // can add props and methods
    size:string = 'm';
}

const jane : Person = {
    name :'Jane',
    age:46,

    // cannot add more proprs or methods
    //size:'s'
}
nadav
  • 552
  • 5
  • 11
3

type in the typescript is used to reference already existing types. It can not be extended like interface. Examples of type are:

type Money = number;
type FormElem = React.FormEvent<HTMLFormElement>;
type Person = [string, number, number];

you can use Rest and Spread in types:

type Scores = [string, ...number[]];
let ganeshScore = ["Ganesh", 10, 20, 30]
let binodScore = ["Binod", 10, 20, 30, 40]

Interface, on the other hand, allows you to create a NEW TYPE.

interface Person{
  name: string,
  age: number, 
}

Interface can be extended with extends keyword.
interface Todo{
  text: string;
  complete: boolean;
}

type Tags = [string, string, string]

interface TaggedTodo extends Todo{
 tags: Tags
}
udeep shrestha
  • 912
  • 11
  • 11
1

Also, an interface can be implemented.

Dave Ford
  • 1,956
  • 5
  • 19
  • 25