Tomas Eglinskas
Tomas Eglinskas

Reputation: 855

Angular 2 models: interface vs classes

I have a login/registration module and I want to write a model for them.

I would use interfaces, but I need to have one predefined value.

And I was wondering - should I put the predefined out as a constant (it won't be changed, altered) and use interfaces. Or write it as classes (as currently)

Currently, I wrote two separate classes - registration.model.ts, login.model.ts, could I be able to abstract to use only one model? (example: user.model.ts)

Some examples:

export class LoginUser {
  constructor(
    private email,
    private password,

    // I need to have it, backend expects it to be sent
    private connection = 'Username-Password-Authentication'  
  ) { }
} 


export class RegistrateUser {
  constructor(
    public name: string,
    public lastName: string,
    public email: string,
    public password: string,

    // I need to have it, backend expects it to be sent
    private connection = 'Username-Password-Authentication'
  ) { }
}

Upvotes: 8

Views: 15586

Answers (2)

jarodsmk
jarodsmk

Reputation: 2099

just came across your question & was investigating the same thing.

With reference to the Angular 2 Style docs here, the 'guideline' is to NOT implement an interface on the premise that a class alone can:

  • Act as an interface (if you use the implements keyword instead of the extends keyword)
  • Be smaller than a class-implementing-interface

As a rule of thumb:

Angular Guidelines > Typescript Guidelines (in the case of Angular 2 projects).

Hope this helps you out! :)

Upvotes: 4

Aluan Haddad
Aluan Haddad

Reputation: 31823

I would definitely use interfaces. It is a simple approach and follows the TypeScript recommendations for working with JSON.

The property in question,

private connection = 'Username-Password-Authentication';

can well be added by the service that performs the request.

This will also reduce code duplication because you can use a generic function or service to create this request object.

For example:

export default function withRequiredAuthProps<T>(model: T) {
  return {...model, connection: 'Username-Password-Authentication'};
}

Then your Http service that sends the model back to the service can use a type constraint to verify that the property has been added before making the request

For example:

export default class MyHttpClient {
  post<T extends {connection: 'Username-Password-Authentication'}>(url: string, body: T) {
    //...
  }
}

These are just meant as examples but they are based on code that is minimal, and that works.

Upvotes: 1

Related Questions