DEV Community

Cover image for Learn about difference between Type & Interface in Typescript

Learn about difference between Type & Interface in Typescript

Code Oz on March 08, 2021

If you are using typescript, you might use interface & type but if I ask you the difference between them, are you able to answer it ? At the e...
Collapse
 
faiwer profile image
Stepan Zubashev

What interface can do, and what type cant do. A class can implement an interface

type A = { a: number };
class B implements A { 
  a: number = 1; 
}
Enter fullscreen mode Exit fullscreen mode

no errors

Collapse
 
fullstackchris profile image
Chris Frewin

Coming from somewhere like C# a class implementing a type is kind of... weird... Though, all instances of a class automatically are that type... so it makes sense in a weird way too.

Collapse
 
codeoz profile image
Code Oz

Hey ! thank you for your comment, I miss something wrong since a few time, this is available ! I edit my article thank you :)

Collapse
 
bravemaster619 profile image
bravemaster619

In a word, interface for OOP, type for FP

Collapse
 
peerreynders profile image
peerreynders • Edited

FYI: A class implicitly exposes an interface that can be merged into - example:

type CompareFn = (lhs: number, rhs: number) => number;

const sortWith: (a: readonly number[], f: CompareFn) => number[] = (
  array,
  fn
) => array.slice().sort(fn);

const ascending: CompareFn = (lhs, rhs) => lhs - rhs;
const descending: CompareFn = (lhs, rhs) => rhs - lhs;

class Container {
  readonly #values: readonly number[];

  constructor(values: number[]) {
    this.#values = Object.freeze(values.slice());
  }

  get values(): readonly number[] {
    return this.#values;
  }
}

interface Container {
  ascending(): number[];
  descending(): number[];
}

function asc(this: Container): number[] {
  return sortWith(this.values, ascending);
}

function desc(this: Container): number[] {
  return sortWith(this.values, descending);
}

Container.prototype.ascending = asc;
Container.prototype.descending = desc;

const container = new Container([10, 45, 15, 39, 21, 26]);
console.log(container.values);
console.log(container.ascending());
console.log(container.descending());
Enter fullscreen mode Exit fullscreen mode

playground

Collapse
 
codeoz profile image
Code Oz

Nice remark I learn something thank you bro !

Collapse
 
flutch profile image
flutch

Nice Article CodeOzz !

Collapse
 
rayleigh93 profile image
Rayleigh-Sama

Just follow you nice content man

Collapse
 
tcelestino profile image
Tiago Celestino

Great. When I started to learn about TS, this topics confuse to me.

Collapse
 
codeoz profile image
Code Oz

thank you Tiago

Collapse
 
king11 profile image
Lakshya Singh

A type can have circular dependencies while interface can't it's super cool to try :)

Collapse
 
codeoz profile image
Code Oz

nice remark Lakshya

Some comments have been hidden by the post's author - find out more