Angular 2 models: interface versus classes

I have a registration / 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 predetermine a constant (it will not change, change) and use interfaces. Or write it as classes (as of now)

Currently, I have written two separate classes - registration.model.ts, login.model.ts, can I 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' ) { } } 
+7
angular typescript
source share
2 answers

I would definitely use interfaces. This is a simple approach and follows TypeScript guidelines for working with JSON.

Own property

 private connection = 'Username-Password-Authentication'; 

may be added by the service executing the request.

It will also reduce code duplication, because you can use a common 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, which will send the model back to the service, can use a type constraint to make sure 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 examples, but they are based on minimal code, and it works.

+2
source share

just stumbled upon your question and studied the same thing.

As for Angular 2 style documents here , the “directive” is NOT to implement an interface based on the fact that the class can:

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

Usually:

Angular Recommendations > Typescript Recommendations (in case of Angular 2 project).

Hope this helps you! :)

+3
source share

All Articles