DEV Community

Gleb Irovich
Gleb Irovich

Posted on

Why using JS classes instead of Typescript interfaces?

As you know, in Typescript one might use JS classes as interfaces.

interface Post {
  title: string;
}

class Post {
  title: string;
}
Enter fullscreen mode Exit fullscreen mode

What are the advantages of using classes (if any) instead of interfaces?

Top comments (3)

Collapse
 
ricobrase profile image
Rico Brase

Usually in Typescript, interfaces are used to describe the structure of an object, just as in your example.

classes usually contain actual behaviour code in them. In default configuration (strict: true), Typescript will complain about

class Post {
  title: string;
}

with the following error message:

Property 'title' has no initializer and is not definitely assigned in the constructor.


Additionally, interfaces are purely used in type-checking, since they don't exist in Javascript - they don't get any compilation output! If you create a post.ts file and fill it with your example code from above, your compiled post.js file will only contain

class Post {
}
Collapse
 
macsikora profile image
Pragmatic Maciej

Class has runtime representation whereas interface hasn't. It means that when you make a Class you get type + value constructor by "new" keyword. In other hand when you make an interface you have type but no value constructor, so you need to make the value separately.

Collapse
 
jwp profile image
John Peters

They are the same thing except in a class you can provide values to properties and write functions.