Methods of using TypeScript in VUE

What is TypeScript

TypeScript is a super-collection of JavaScript, which means it supports all JavaScript syntax. It is very similar to JavaScript stronger version, in addition to this, there are some extension syntax, such as Interface / Module. TypeScript will remove types and unique syntax in compile periods to generate pure JavaScript.

TypeScript has a trend of temperature over time in 5 years, and the overall trend is presented as a whole. It also shows that TS is getting more and more attention.

Vue 中使用 typescript的方法详解

Installing TypeScript

NPM INSTALL-G TypeScripttsc Greter.ts
   
Lifts a chestnut

It can be seen that TypeScript will remove type and unique syntax in the compile period, generate pure JavaScript. Greter.ts

Interface: String; Lastname: string;} Function Greter (Person: Person) {Return “Hello,” + Person.Firstname + “” + Person.lastName;} let user = {firstname: “jane”, Lastname: “user”};

 Greter.js   
FunctionGreter (Person) {Return “Hello,” + Person.Firstname + “+ Person.lastName;} var user = {firstname:” jane “, Lastname:” user “};

Why do you need to use it?
   
Static Type Check
Ide Intelligent Tips

Code Reconstruction

Readability
  1. 1. Static Type Check
  2. Static Type Check the primary advantage is to discover logic errors as soon as possible, not after the line is online.
  3. 1.1 Type Analysis
  4. Transmission process field error, or type error is used. (After the parameter is labeled, the error can be checked during the encoding process.)
  5. 1.2 Type Inference: The return value of the function can be derived by the TS type. This step is compiled when compiling. Type analysis

EXAMPLE: EG1: I found a problem when using the dynamic path parameters of the TS Write Vue-Router, and the dynamic path parameters started with the colon PATH: ‘/ user /: id’, we will Mistlers Id as a Number, if you use TS, you will get prompts to get into a string type ID. Incoming an ID of a Number type may not be wrong, JS will make it implicit type conversion, but incoming A String will make it safer and specification.

Interface Person {FIRSTNAME: STRING; Lastname: string; Function GreeterPerson: Person): String {return “Hello,” + Person.Firstname + “+ Person.lastname;} let user = {firstname: 1223, lastname:” user “}; Greter (user);

2. Intelligent completion

When writing code, Ide is prompting the function signature.
   Interface Person {FirstName: String; LastName: String;} / ** * Greeting statement * @Param {Person}: string {return: string {return: string {return "Hello," + Person.Firstname + "+" + Person.lastName;} / ** * Hello Word! * * @Param {string} Word * @returns {string} * / function hello (Word: string): String { Return "Hello," + Word;} export {Greter, Hello}; 
Directly introduced this TS file into other TS files, not only all parameters Type, also tell you that you need to fill in a parameter and you only have an object that is filled in a Person type. (Intelligent completion and parameter check)

Vue 中使用 typescript的方法详解 3. In the reconstruction

Dynamic is cool, refactoring the crematorium.

TypeScript has the advantage of refactoring, and we mainly explained three aspects.

Renovate symbols to modify all references.
 In VS Code If we want to modify functions, variables, or classes, we can use the functionality of rename symbols, correctly modify all references in the current project. This can be used in TS, It can also be used in JS, and its underlying implementation is implemented by the syntax analyzer of the TS.   Automatically updates the reference path (VS code). 
In the process of reconstruction, we may need to move file paths, which often leads to Import failures in other places, this time vs code provides the function of automatic update reference paths. Its underlying implementation is also achieved by the syntax analyzer of the TS.
Check function signature.

Sometimes we will retrieve the signature of the function or function. If there is a reference to the place to forget the modification, in addition to running, it is often difficult to detect at other times, and ESLINT can only be a simple investigation. The problem, so it will be very troublesome of BUG. TypeScript is different. When you encode, you can find it wrong in time, where you should change but no modification. Vue 中使用 typescript的方法详解

[5]

4. Readability

On readability, TypeScript is obviously dominant, view open source code If the comment is not very perfect, it often looks in the clouds, and TypeScript is under the same conditions, at least one type, which makes it easier for yourself to understand the parameters of the code, return value, and intentions.

TS + VUE A Probe into

Configuration
  • We need to know some basic configurations before formally developed.
  • Tsconfig.json is the compilation option configuration file for the TS project. In TSIf you don’t add this file, TS will use the default configuration. Scan the QR code to get the configuration item.
  • TS-Loader: WebPack’s TypeScript loader is to make WebPack compile .ts .tsx files.
  • TSLINT: .TS .TS .TSX file code style check tool. (Actually similar to eslint)
  • Vue-shim.d.ts: Due to TypeScript defaults to * .vue suffix files, you need to create a Vue-Shim.D during the Vue project. The TS file is placed in the root directory, such as SRC / Vue-Shim.d.ts.

The manner in which the TS is written in Vue

, the content should be written in the lang = “TS” in the script.

Distraction: Basic usage using Vue.extend.

Based on class-based VUE component

By

, we found that the above encoding method is closer to us. The usual JS is written, but we can’t feel the type check and type inference of TS. The writing of the following sheet will help us get TS type check. This requires us to introduce Vue-Class-Component, although it is still completed in Template, but the content in Script has been better completed. Let’s take a look at the role of Vue-Class-Component.

Vue-Class-Component & Vue-Property-Decorator

Vue 中使用 typescript的方法详解 Vue-Class-Component enhances VUE components, uses decorator syntax to make VueThe components are better in combination with TS. Vue-Property-Decorator adds more decorators associated with Vue to the Vue-Class-Component to make the VUE components combine with TS.

    Both of these are inseparable from the decorator, and the (Decorator) decorator has been in the ES proposal. Decorator is the practice of decorator mode. Decorator mode, it is an alternative to inheritance relationship. Dynamically add additional responsibilities to the object. Enhance the performance of the class without changing the interface. Below we use the Iron Man as an example to explain how to use the ES7 Decorator.
  1. Taking the Iron Man as an example, the nature of Iron Man is a person, but “decoration” has become so NB, but then how to decorate him or alone, it is not changed. Therefore, the decorator does not change its inheritance, but it also can add a lot of power to it. Simply put, the decorator is modified or add member to a class without modifying a class’s inheritance relationship.
  2. Three parameters of the main receiving of the decorator: Target To define the object of the attribute. Key to define or modify the name of the attribute. Descriptor will be defined or modified attribute descriptors. Below we have added flights to a person through the code:
TypeScript vs JavaScript

Vue 中使用 typescript的方法详解 Understand the above basic knowledge, now I will A piece of code uses JS and TS to write, now we will compare the differences between them.

PROPS (Properties) uses JS, we have many middle methods to define the PROPS of the component, but most of them are doped with the private features of the Vue, with the ES grid, such as left The code, obvious that we are defined by this object’s prop attribute into an object containing two string elements, but we can pass directly.This object comes to access the “name” field, which is clearly not in line with ES semantics. Let’s take a look at the TS player on the right. Tag the specified field with the specified field by the Prop Decorator, which is preserved in the Semantic Semonary, and more well, better, we can enjoy it in the process of encoding TS checks for static types of PROP fields. Method and Data Take a look at Method, and JS define Method or there is a problem that we don’t meet ES semantic. In TS, Method does not require additional decorator – instance method automatically becomes the Method of the VUE component. Similar to DATA, using TS’s grammar, instance fields automatically become the DATA of the VUE component. Computed In the VUE code written in JS, computed, if you want to define the calculation properties, we need to define the corresponding function in the compute property. And this has already had a corresponding semantic syntax – Getter in ES, so in the Vue component of Vue-Class-Component, we can use the getter to define the calculation properties, whether it is still in the grammatical Summary, compared to ordinary JS is slightly banned

summary: We use Vue-Class-Component to make the definition of the VUE component more in line with ES, so that TS can better analyze grammatical analysis, based on this Type check.

Use TS + VUE

Vue 中使用 typescript的方法详解 in the business scene. Define DATA and PROPS

in the Vue project, such a way of writing, let me I have two doubts.

1. Why is the Writing @Prop (Number! 🙂 Propa !: Number instead of @Prop (Number) Propa: Number Vue 中使用 typescript的方法详解

1.2 Why is the PROP needs to write twice before and after?

Self-Answers:

Answer 1.1: Because we set a Phone this class, there is no pHONE, CONDition these fields are initialized by constructor, so you need to use explicit assignment to asserts on attributes. Help Type System Identification Type, which enables properties to initialize indirectly. Answer 1.2: Types in front brackets Tags are the type check provided by Vue. The colon is labeled for TS. 2. Write a function

Here we will use the JS interface, which is often used to define complex parameter types and return value types.

The above example, we need to define the type of the parameter for the OPTS, which is convenient for use when encoded later, then we need to write an interface to define it. This interface includes three must attributes and an optional properties. You must assign a value when the object is initialized, but sometimes the properties in an object can be ignored, and it is not necessarily required. We can set it to optional.

With the development of the business, some parameters will become more and more complicated. Maybe you want to have any way to benefit for all, so that the interface is simpler, even let it automatically adapt to the business. So I came up with this code:

Vue 中使用 typescript的方法详解

The above code: Defines a key to string, his value is an interface of Number or String type, and the interface All fields are optional, you can even get an empty object. So we can use the above interface to replace the following interface, but it will not be possible.

Vue 中使用 typescript的方法详解 However, we should not go around these checks, because this TS will not check the objects that should be used to use the interface should exist. Or method. The meaning of using TS is greatly weakened.

3. Writing Third Party Dependency

During the daily development process, we often encounter problems that have not been introduced into the TS project in the TS project in the TS project, which is often because of these Project does not provide typeRighteous file. At this time, we can manually write type definition files for these third-party libraries, and the type definition file is completely ignored after compiling, so it does not have an impact on existing code. Take the more complex function above as an example, its role is to merge all the fields of all the parameters into a new object and return it, although his function is relatively simple, but write type definitions for it. Ts’s skills.

Vue 中使用 typescript的方法详解 1. External module declaration: First we need to create a file that expands the name .d.TS, and declare a module, the declared module name needs to be followed us. The path introduced in other files is the same.

2. Type parameters – generics: First let us consider the simplest case, when passing into a parameter, the extend function should return the same parameter type. Object, but we don’t know what type of parameters that users will pass during writing functions, so we can define a type parameter T1. At this time, Extend is called generic functions, T1 is also known as generics parameter. In the above example, the Extend function accepts a value of a type T1 parameter and returns a type T1. T1 requires the user to manually introduce, but the TS is sufficiently smart, in most cases, TS can automatically according to the parameter type Introducing type parameters, eliminating the cumbersome steps of our input type parameters. The extend function that only accepts a parameter is not very complicated, we can continue to consider some more complex situations.

This time, let us define an Extend function that accepts three parameters, and it also accepts three generic parameters, and it returns the value type, then T1, T2, T3 cross type. The cross type allows us to make existing types of types together into a type, which contains all types of features required, equivalent to the consumption set of these types. For example, T1 & T2 & T3 This type of object has three types of members. Here, the cross type satisfies our requirements for the return value of the extend function. Pay attentionIt is, the actual Extend function can accept the parameters of the number of numbers, that is, we need to be compatible with the type definitions you have to accept, which requires the function overload function provided by TS.

3. Overload: In most static type programming languages, the compiler allows the parameter type, the number of different types of symbols, this feature is called The function is overloaded. The TS supports the characteristics of the function overload, so we can define multiple Extend methods that accept different quantities, when the user calls, TS automatically selects the correct overload definition in these same name functions. With the help of the function overload, we can enjoy the benefits of type checks in most scenes using Extend, and TS cannot infer the return value type when the number of parameters exceeds 4. It should be noted that in JS, it does not provide the ability to overload when running, we cannot define multiple symbol functions, even if they accept the number of parameters, the developer needs manual in order to implement the effect of the function overload. The type and quantity of the parameters are judged in a single function. Vue 中使用 typescript的方法详解

Here our third party statement is completed, even if a third party statement of a simple function, we also use a lot of TS related knowledge.

We explained before, using TS in Vue to bring us convenience, now I am personal feeling, talk about it in the United States The place.

1. Even if the TS is used, the Template section still does not have a static type check and IDE smart prompt, but the official member means that this function will be provided in the later VUE single file. 2. Introduce the VUE single file component into the TS file, which cannot prompt its file location. 3. Vuex, such as VUEX, is weak to TS, and a large number of functions are difficult to directly migrate to TS, and there is no good official support. 4. There is no doubt that use TS for development, compared to JS, we need more time and effort.

Summary

The above is the use of TypeScript methods for the use of TypeScript, I hope to help everyone! Vue 中使用 typescript的方法详解

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment