B
B
BonBon Slick2020-05-25 21:40:45
typescript
BonBon Slick, 2020-05-25 21:40:45

What are interfaces in Vuex modules for?

Here is an example of what I mean, what would be done more With like? After all, it was possible to do without it and use, for example, just a class, I don’t understand why this layer

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  public token : string = getToken() || ''
  public name : string = ''
...

and less code.
And where it is necessary to use the user as a type, set User instead of IUserState

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Robur, 2020-05-26
@BonBonSlick

For more structured code.
You thus formally separate "UserState" from everything that this UserState can implement.
it can be used not only in the User class, but also in other places.
For example, I needed RandomUser, which makes all fields random. but it can be used interspersed with User, because it also has the UserState interface. At the same time, it does not have half of the methods that User has, so you cannot use it where you write the User type.
You will need to write "User | RandomUser". this is not very good, but what if there are 10 different ones?
And if in some place they wrote 8 and forgot about two? And in another place 8 was written and 2 was not written, because there can really be one of 8 types and those two cannot be.
And if we have a user type "boss" that has all the fields that the user has but also an additional field "employees"? And there are several such types. And somewhere you need to make sure that this is the type of the variable. Etc.
Explicitly defined interfaces allow you to separate all these entities from the rest of the code, structure this code much better and keep it in order with less effort. And he is getting smaller too.
BUT! If you have a dozen classes in an application, and each class corresponds to one interface, then there is little benefit from this approach. You can not write these interfaces. This comes from OOP, where they solve problems that arise in applications with hundreds of entities and classes, complex hierarchies, and so on.

V
Vladimir Korotenko, 2020-05-25
@firedragon

typescript thinks for you and shows where possible errors are, well, some sugar.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question