loading...

Why using JS classes instead of Typescript interfaces?

glebirovich profile image Gleb Irovich ・1 min read

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

interface Post {
  title: string;
}

class Post {
  title: string;
}

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

Discussion

markdown guide
 

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 {
}
 

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.

 

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