The difference between interfaces and classes in Typescript

What are the different Typescript interfaces and classes? When do I use a class? When do I use interfaces? What are their advantages?

I need to create some types for the http request on my backend server (Doing it with Angular 2), for example:},

"fields": { "project": { "id": "10000" }, "summary": "something wrong", "issuetype": { "id": "10000" }, "assignee": { // not neccesary required "name": "homer" }, "reporter": { "name": "smithers" }, "priority": { // not neccesary required "id": "20000" } } 

What should I use to create these models? Thanks!

+20
class interface angular typescript models
source share
5 answers

2019: update on differences and uses

First, there is an obvious difference: syntax. This is simple, but necessary to understand the difference: interface properties can end with semicolons or semicolons, however class properties can end only with semicolons. Now interesting things. The sections on when to use and not to use can be subjective - these are recommendations that I give to people on my team, but it is possible that other teams will have different recommendations for valid reasons. Feel free to comment if your team does it differently, I would like to know why.

Interfaces : allow you to determine the type that will be used during development, and compilation time for strong typing. They can be "implemented" or "extended", but they cannot be created (you cannot new them). They are deleted when ported to JS, so they do not take up space, but they also cannot be checked for type at runtime, so you cannot check if a variable implements a certain type at runtime (for example, foo instanceof bar ), except checking the properties that it has: Checking the type of interface using Typescript .

When to use interfaces : use them when you need to create a contract of properties and functions for an object that will be used in several places of your code, especially in several files or functions. Also use when you want other objects to start with this basic set of properties, for example, with the Vehicle interface, which several classes implement as specific types of vehicles, such as Car , Truck , Boat (for example, class Car implements Vehicle ).

When not to use interfaces : When you want to have default values, implementations, constructors or functions (and not just signatures).

Classes : also allow you to determine the type that will be used at design time and compilation time for strong typing and, in addition, can be used at run time. It also means that the code is not compiled, so it will take up space. This is one key difference mentioned by @Sakuto, but it has more consequences than just space. This means that classes can be typed, while retaining an understanding of who they are even in the transmitted JS code. Further differences include: classes can be created using new and can be extended, but not implemented. Classes can have constructors and the actual function code along with default values.

When to use classes : when you want to create objects that have valid function code, there is a constructor for initialization and / or you want to instantiate them using new . Also for simple data objects, you can use classes to set default values. Another time you want to use them is when you perform type checking, although there are workarounds for interfaces if necessary (see the OS section of the link section).

When not to use classes : when you have a simple data interface, you donโ€™t need to instantiate it when you want it to be implemented by other objects, when you just want to put the interface into an existing object (think of type definition files) or when space, which it takes is prohibitive or unreasonable. As a side note, if you look at the .d.ts files, you will notice that they only use interfaces and types, and thus this is completely removed when passed to TS.

Last note , there are two other options besides classes and interfaces, the first of them is called โ€œtypeโ€, which is very similar to the interface, but look at this SO post, in particular, the answer to the 2019 update: Typescript: Interfaces vs Types . The final option is to use a functional programming style (not OOP) with TS.

For a complete history with examples, visit PassionForDev.com, and for more information on classes and inheritance with examples, visit https://jameshenry.blog/typescript-classes-vs-interfaces/ .

+15
source share

According to the Angular 2 style guide, it is recommended that you use Class over Interface for typing . The main difference is that the class will be preserved during compilation, while the Interface is deleted only because it is not used.

Just stay consistent throughout the project and prefer a style approach to the class that knows, maybe one day you will need to add a method to your models .

Check the answer below for more details: fooobar.com/questions/843313 / ...

+20
source share

It's just that the class is designed to create objects, and the interface helps you what these objects should contain.

A class is like a template / template with which we can create objects. An interface is similar to a contract by which a class must agree on the implementation of this interface or determine what this plan should contain.

Simple class:

 class Car { engine: string; // 'var' is not used; constructor(engine: string) { // This is how we create constructor this.engine = engine; } display(): void { // 'function' keyword is not used here. console.log('Engine is ${this.engine}'); // just a log. } } var objCar = new Car('V8'); // creates new onject objCar.display(); // output: Engine is V8 console.log(objCar.engine); // output: V8 (accessing member here) 

Simple interface:

  interface IPerson { // This is how we create an interface. firstName: string, // use commas to separate. lastName: string, // In classes we use semi-colon to separate. displayDetails: (number) => string } // We are going to store 'interface object' in a variable. // ie we are implementing interface with variable(not class!!) var customer: IPerson = { firstName: 'jose jithin', // 'implements' variables lastName: 'stanly', // Now method implementation. // Note: the syntax of 'displayDetails' maybe a bit confusing (given below) // as two colons are used. // It specifies a return type(string) here for this method. displayDetails: (rank): string => { return 'This person has rank ${rank}. ' } // It can be rewritten as following too. displayDetails: (rank) => { return 'This person has rank ${rank}. ' }; // ie return type need not be specified, just like a normal method definition syntax. } console.log(customer.firstName); // output: jose jithin console.log(customer.lastName); // output: stanly console.log(customer.displayDetails(1)); // output: This person has rank 

I described the class and interface in detail in my article . It can help you understand.

+6
source share

Use typing to create a data model instead of a class, since the compiler will not generate the appropriate JavaScript code for the interface at runtime. Whereas if you use a class to easily create a data model, then the compiler will create the appropriate JS code for it, therefore, it will take up memory.

Snippet from Angular style guide: https://angular.io/guide/styleguide#interfaces

"Consider using a class instead of an interface for services and declarations (components, directives, and channels)."

" Consider using an interface for data models. "

+4
source share

I use angular last 2 years and in simple words, when I want to add any behavior to my object, I use a class, for example, for any class, I want to add a get method that returns processed data, and when there is no behavior added to the object and I want to get direct access to the object. I will use the interface. Using a class, if you define a constructor, you restrict the user to defining a specific variable to initialize before creating any object.

0
source share

All Articles