254

I recently watched a Tutorial on Angular 2 with TypeScript, but unsure when to use an Interface and when to use a Model for data structures.

Example of interface:

export interface IProduct {
    ProductNumber: number;
    ProductName: string;
    ProductDescription: string;
}

Example of Model:

export class Product {
    constructor(
        public ProductNumber: number,
        public ProductName: string,
        public ProductDescription: string
    ){}
}

I want to load a JSON data from a URL and bind to the Interface/Model. Sometime I want a single data object, other time I want to hold an array of the object.

Which one should I use and why?

4
  • 18
    Use a class when you need custom logic init, otherwise always use an interface since this is only available at compile time. A typescript interface is not compiled to javascript since it does not exist in javascript.
    – Dieterg
    Commented Jun 6, 2016 at 8:43
  • 6
    Keep in mind that interfaces will NOT work with dependency injection in Angular 2. Here you will have to use classes.
    – jlang
    Commented Feb 14, 2017 at 10:36
  • 1
    This article codefeetime.com/post/typescript-class-or-interface-for-model seems to suggest that you will need custom logic most of the times. Covers the topic pretty well imho.
    – oomer
    Commented Feb 11, 2022 at 0:14
  • If you object has only data and doesn’t have a behaviour, use interface stackoverflow.com/questions/41067961/… Commented Dec 31, 2023 at 3:20

7 Answers 7

169

Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:

this.http.get('...')
    .map(res => <Product[]>res.json());

See these questions:

You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:

this.http.get('...')
    .map(res => {
      var data = res.json();
      return data.map(d => {
        return new Product(d.productNumber,
          d.productName, d.productDescription);
      });
    });
12
  • 30
    Thanks for your detailed answer. If the interface is only used at compile time, how can the compiler check the structure of the JSON file without actually examining the http get? If it can't, then what is the point of even bothering with an interface?
    – I_LIKE_FOO
    Commented Jun 6, 2016 at 11:01
  • 11
    @I_LIKE_FOO the compiler doesn't need to examine the get call. It only cares about checking the types it knows about and that they are correctly aligned. var data = res.json(); is really var data: any = res.json(); to the compiler so we lose all type checking on data. What would be more useful here would be something like var data: ProductDto[] = res.json(); with ProductDto being an interface that models the data structure in the returned json.
    – GFoley83
    Commented Feb 21, 2017 at 6:10
  • 5
    Yes, but the problem is they are not the guru gods who engineered Typescript. That would be Microsoft and company. They tend to favor interfaces, and classes when appropriate. Also bonus points ... one is runtime and other is at compile time Commented Sep 21, 2017 at 8:23
  • 14
    @Sampath Perhaps the Angular style guide has been updated as I now see this "Consider using an interface for data models.". Implies prefer interface over class for data models.
    – Mikezx6r
    Commented Feb 6, 2018 at 13:19
  • 4
    One thing that I came across and seemed worthy of sharing here is that - as interfaces are just compile time entities and are removed from the run time bundles in dists, but classes remain there in run time dists. Our class is being transpiled into its ES5-compatible function form, and is now an unnecessary part of our final JavaScript application. If we had a large application, and repeated this pattern of using classes as model type annotations, then we could end up adding a lot of extra bloat to our users’ bundles.
    – Shiv
    Commented Mar 14, 2019 at 11:50
50

The Interface describes either a contract for a class or a new type. It is a pure Typescript element, so it doesn't affect Javascript.

A model, and namely a class, is an actual JS function which is being used to generate new objects.

I want to load JSON data from a URL and bind to the Interface/Model.

Go for a model, otherwise it will still be JSON in your Javascript.

0
38

I personally use interfaces for my models, There hoewver are 3 schools regarding this question, and choosing one is most often based on your requirements:

1- Interfaces:

interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once your code is transpiled to its target language, it will be stripped from its interfaces - JavaScript isn’t typed.

interface User {
 id: number;
 username: string;
}
// inheritance
interface UserDetails extends User {
 birthdate: Date;
 biography?: string;  // use the '?' annotation to mark this property as optionnal
}

Mapping server response to an interface is straight forward if you are using HttpClient from HttpClientModule if you are using Angular 4.3.x and above.

getUsers() :Observable<User[]> {
 return this.http.get<User[]>(url); // no need for '.map((res: Response) => res.json())' 
}

when to use interfaces:

  • You only need the definition for the server data without introducing additional overhead for the final output.
  • You only need to transmit data without any behaviors or logic (constructor initialization, methods)
  • You do not instantiate/create objects from your interface very often
    • Using simple object-literal notationlet instance: FooInterface = { ... };, you risk having semi-instances all over the place.
    • That doesn't enforce the constraints given by a class ( constructor or initialization logic, validation, encapsulation of private fields...Etc)
  • You need to define contracts/configurations for your systems (global configurations)

2- Classes:

A class defines the blueprints of an object. They express the logic, methods, and properties these objects will inherit.

class User {
 id: number;
 username: string;
 constructor(id :number, username: string)  {
  this.id = id;
  this.username = username.replace(/^\s+|\s+$/g, ''); // trim whitespaces and new lines
 }
}
// inheritance
class UserDetails extends User {
 birthdate: Date;
 biography?: string;  
 constructor(id :number, username: string, birthdate:Date, biography? :string )  {
   super(id,username);
  this.birthdate = ...;
 }
}

when to use classes:

  • You instantiate your class and change the instances state over time.
  • Instances of your class will need methods to query or mutate its state
  • When you want to associate behaviors with data more closely;
  • You enforce constraints on the creation of your instaces.
  • If you only write a bunch of properties assignments in your class, you might consider using a type instead.

3- Types:

With the latest versions of typescript, interfaces and types becoming more similar. types do not express logic or state inside your application. It is best to use types when you want to describe some form of information. They can describe varying shapes of data, ranging from simple constructs like strings, arrays, and objects. Like interfaces, types are only virtual structures that don't transpile to any javascript, they just help the compiler making our life easier.

type FamilySituation = 'single' | 'married' | 'divorced' | 'widow' ;...
type User = {
 id: number;
 username: string;
}
// inheritance
type UserDetails = User & {
  birthDate: Date;
  familySituation: FamilySituation ;
}

when to use types:

  • pass it around as concise function parameters
  • describe a class constructor parameters
  • document small or medium objects coming in or out from an API.
  • they don't carry state nor behavior
5

As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.

4

Use interface when you just want to check for data type in order to make sure the response always has the necessary keys. Classes/models for more than just checking for data types. Plus, good to know that interfaces doesn’t exist in javascript which means typescript will always handle interfaces at compile time unlick classes which are native to javascript.

0

In order to make your code flexible, we need to use interfaces. Create interfaces and pass the interface type in the constructor of class. This uses dependency injection.

Benefits:

  1. If there is change in the parameters of the interface, No need to change class. 2.For testing you can use mock data in constructor of class.
-30

Use Class instead of Interface that is what I discovered after all my research.

Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

from Angular Style Guide

Basically a Class can do all, what an Interface will do. So may never need to use an Interface.

3
  • 12
    The Angular Style Guide currently actually says, “Consider using an interface for data models. Commented Jun 15, 2018 at 17:07
  • 1
    @AlexPeters Please provide any authentic link. Thanks in advance Commented Apr 12, 2020 at 18:21
  • 1
    @AnandPhadke sure, here's a Wayback Machine link to the Angular Style Guide from around the time of my comment above. Commented Apr 13, 2020 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.