Maybe it's different from others. I use TypeScript to write the front end

original
2023/08/16 15:09
Reading 568

Open source code:>Github: https://github.com/HammCn/AirPower4T > > Gitee: https://gitee.com/air-power/AirPower4T

1、 Some current write front-end operations

Please list some writing methods you have seen:)

1. Interface (or Type) A shuttle

Many articles on Nuggets mentioned TypeScript , you can't use it first interface perhaps type To declare a data structure? like this:

 type User = { nickname: string avatar?: string age: number } interface User { nickname: string avatar?: string age: number }

Then other methods limit the input parameter type. I have mastered it TypeScript My salary cannot be increased by 3000???

>Let me explain that our company not allow Direct use interface type To define non decorator parameters and other configuration parameters Any data type

2. Type gymnastics whole flower activity

Either the attribute is read only, or the pig and dog types are combined, or the pig tail is lost, or the bull will really brag.

Type gymnastics does play a lot of tricks. Yesterday said: TypeScript is the most interesting type gymnastics, which is also the last thing to appear

three hook The Infinite Myth of

I don't know when to start, hook More and more popular. I heard that I can't write hook The front-end programmer of use Nothing shows the level of excellence.

four axios Intercept Dafa Okay

Search casually axios 's article, no Interceptor None of the articles with this keyword can be counted as axios The high-end usage of.

2、 We have some different front-end operations

Yesterday's article mentioned some information about the use of Decorator To implement some requirements based on configuration, today I want to focus on how to talk about elegant object-oriented in the front end.

Yes Java SpringBoot JPA Some concepts that back-end programmers should be familiar with:

  • Abstract: Everything can be abstracted into related classes and objects
  • Object oriented: Object oriented design thinking with inheritance, encapsulation, polymorphism and other characteristics
  • Section: Nothing can be solved by cutting with one knife. If one knife can't do it, then add more.
  • Note: There are no constants that cannot be configured with notes, and there are no notes that can be avoided if you want to cut them
  • Reflection: Nothing is violent and will fail. Even if it fails, there is no exception that cannot be thrown out
  • Entity: nothing can not be abstracted to entity, everything is unique.
  • Many: There are many more. The above description is subjective and casual.

So we began to transfer the back-end thinking to the front one by one:)

1. Abstract and object-oriented

The interaction data object and request API interface with the back end are abstracted to specific classes, so there are:

  • Service API request class
 abstract class AbstractService{ //Implement an abstract attribute so that subclasses can implement abstract baseUrl!: string //Then implement some common network requests such as adding, deleting, modifying and querying // save() // getDetail() // deleteById() // select() // page() // disabled() // ...... }
  • Entity Data Entity Base Class
 abstract class AbstractBaseEntity<s extends abstractservice> { abstract service: AbstractService //Any data is a unique ID id!: number //Then implement some methods of updating and deleting data entities save(){ await service.save(this.toJson()) Notify. success } delete(){ service.deleteById(this.id) Notify. success } // ...... }
  • Implementation of subclasses:)
 class UserEntity extends AbstractUserEntity<userservice>{ service = new UserService() nickname!: string age!: number avatar?: string //Whether the user is an adult isAdult(): boolean{ return this.age &gt;= 18 } }
  • View View call
 <template> <el-input v-model="user.nickname" /> <el button @ click="onUserSave()">Create a user</el button> </template> <script setup lang="ts"> const user = ref(new UserEntity()) async function onUserSave(){ await user.save() } </script>

2. Decorator/section/reflection

Yesterday's article mentioned some of the decorations, but today we mainly talk about reflection and section.

stay TypeScript In fact, the decorator itself can be understood as a section Java There are still many differences, but the concept and thinking are basically the same.

Reflect yes TypeScript The existence of China Comparison Pit is mainly dependent on reflect-metadata This third-party library stores some metadata in metadata It is obtained through reflection when needed. You can refer to this article: Analysis of metadata in TypeScript and implementation principle of reflect metadata

In practice, we used class-transformer This database should have been highly evaluated by me before: "If there is no class transformer library, TypeScript dogs will not write."

It's really a great library, but later, we wrote a general internal framework to adapt WeChat applet as well as uniapp In addition, there are some special business functions and the writing and naming methods of class transformer, which I don't like personally. We gave up this library, but we re implemented an internal library following its idea, and made some function castration and new feature addition.

Some descriptions of core functions

  • Data conversion through reflection

    >If the data returned by the back-end API is forcibly converted according to the data structure of the front-end, when the back-end data is returned in disorder, ensure that the front-end data will not have any problems in use, as shown in the following demo

     class UserEntity { @Type(String) phone!:  string; @Type(RoleEntity) roleInfo!:  RoleEntity: @Type(DeptEntity) @List @Default([]) deptInfoList!:  DeptEntity[] @Type(Boolean) @Default(false) isDisabled!:  boolean }
  • Storage and reading configured through reflection

    >In yesterday's article, we talked about some aspects, such as configuration forms, tables, search boxes, permissions, etc

3. Re emphasize object-oriented

In order to make the whole front-end project engineering, structured and highly abstract, we have to emphasize object-oriented design again:)

  • This is a society of competing for father

    >Once it is possible to reuse some general functions, you can consider and try to let its parent class implement them. If you need a child class to pass in some characteristic parameters, you can use abstract methods or abstract properties (which are not available in Java) to pass in the characteristic parameters required in the implementation of the parent class.

  • Reasonable abstraction layering

    >Some features are combined and separated according to different abstract concepts to realize the function of each class as uncoupled as possible and realize the single responsibility of the class. If multiple inheritance exists, the interface can be abstracted in consideration of the implementation cost of the implementation class interface Medium.

  • There are many more. Please list them again when you have time

4. Strict but interesting tsdoc

Let's take a look at some screenshots of comments:)

Some detailed comments, abandoned methods, optional parameters, and other parameters that may be affected or depended on after the parameters are passed in. Write fun in the comments emoji Or pictures, or even Write and call the demo directly in the comment , so that callers can easily and happily connect calls and play back, which really helps the quality of the overall project.

3、 Write at the end

At noon, I had a lunch with my colleagues and talked about the status of the big front end in China. At that time, I talked about a key word Comfort zone There are also some advantages and disadvantages of the entire front-end technology stack being too flexible. Several elders have expressed some regrets. If the front-end can be more standardized, such as Java Similarly, maybe the front end can rise several heights.

That's all, This concludes today's article on water</ userservice></s>

Expand to read the full text
Loading
Click to join the discussion 🔥 (1) Post and join the discussion 🔥
Reward
one comment
two Collection
zero fabulous
 Back to top
Top