Angular 2 models: interface vs classes

angular, typescript

Solution

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.

Problem

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' ) { } } ```

Original source