Interface vs Type

Mateusz -

TypeScript allows us to define types in two ways. By using Interface and Type keyword. But what are the main differences between these two?

In the beginning TypeScript only had the Interface keyword. Then they introduced the Type keyword, which was a shorter and faster way for defining types.

Interface syntax

//
interface IKeyPair {
    key: number;
    value: string;
}

const keyPair: IKeyPair = { // Good
    key: 1,
    value: '100'
}

const keyPair2: IKeyPair = { // Error, value is missing
    key: 1
}

//with optional property
interface IUser {
    firstName: string;
    lastName: string;
    age?: number;
}

const user: IUser = { // Good
    firstName: 'Hello',
    lastName: 'World'
}

//

Type syntax

//
type TKeyPair = {
    key: number;
    value: string;
}

const keyPair: TKeyPair = { // Good
    key: 1,
    value: '100'
}

const keyPair2: TKeyPair = { // Error, value is missing
    key: 1
}

//with optional property
type TUser = {
    firstName: string;
    lastName: string;
    age?: number;
}

const user: TUser = { // Good
    firstName: 'Hello',
    lastName: 'World'
}
//

Extends

Interface and Type syntax is very similar. We can even extend an Interface with a Type.

//
type TUser = {
   firstName: string;
   lastName: string;
}

interface IUserData extends TUser {
   UserId: string; 
}
//

The important thing to remember is that it does not work the other way round. IUserData must be declared as an interface, not a type, because the extends keyword will throw an error. This is another difference to add.

Declaration merging

It is the first main difference. Declaration merging allows us to create multiple interfaces with the same name and they will be merged at the end.

//
interface ICar {
  color: string
}

interface ICar {
  size: string
}

const car: ICar = { //ICar merged into one interface
  color: 'red',
  size: 'suv'
}
//

Aliases

The other major difference is the possibility to create aliases in Types. Interface does not allow this.

//
type TUserID = number;

function getUserData(id: TUserID) { } //Good
//

const userID: TUserID = 123; //Good
//

Summary

Declaration merging, aliases and extends are the main differences to be aware of between an Interface and a Type.