Using Typescript in Vue

Source: Internet
Author: User
Use typescript in Vue what is typescript

Typescript is a hyper-set of JavaScript, which means it supports all JavaScript syntax. It's much like a JavaScript-strong-type version, besides, it has some extended syntax, such as Interface/module.
Typescript will remove the type and the unique syntax during compile time, generating pure JavaScript.

Typescript in 5 years, the trend of heat changes with time, overall presents an upward trend. It also shows that TS has become more and more ️ by everyone's attention.

Installing Typescript
npm install -g typescripttsc greeter.ts
Give me a chestnut.

By contrast, you can see that typescript will remove the type and syntax at compile time, generating pure JavaScript.
Greeter.ts

interface Person {    firstName: string;    lastName: string;}function greeter(person: Person) {    return "Hello, " + person.firstName + " " + person.lastName;}let user = { firstName: "Jane", lastName: "User" };

Greeter.js

function greeter(person) {    return "Hello, " + person.firstName + " " + person.lastName;}var user = { firstName: "Jane", lastName: "User" };
Why do I need to use it?

Advantage:

    1. Static type checking
    2. IDE Smart Tips
    3. Code refactoring
    4. Readability
1. Static type checking

The primary advantage of static type checking is that logic errors can be discovered as early as possible, rather than on-line.
1.1 Type Analysis
The pass-through procedure field error, or type error is used. (when the parameter is labeled, errors can be checked during the encoding process.) )
1.2 Type inference: The return value of a function can be inferred from the TS type. This step is done at compile time
Type analysis at compile time

Example
EG1: I found a problem when I use TS write vue-router dynamic Path parameter, the dynamic Path parameter begins with a colon path: '/user/:id ', we will mistakenly consider the ID as a number, if using TS you will be prompted We should pass in an ID of type string. Passing in an ID of type number may not be an error, JS implicitly casts it, but passing in a string makes it more secure and canonical.

EG2: The effect after personal use

interface Person {    firstName: string;    lastName: string;}function greeter(person: Person): string {    return "Hello, " + person.firstName + " " + person.lastName;}let user = { firstName: 1223, lastname: "User" };greeter(user);

2. Intelligent completion

The IDE prompts for a function signature when writing code.

interface Person {    firstName: string;    lastName: string;}/** * 问候语句 * @param {Person} person * @returns {string} */function greeter(person: Person): string {    return "Hello, " + person.firstName + " " + person.lastName;}/** * hello word! * * @param {string} word * @returns {string} */function Hello(word: string): string {    return "hello," + word;}export { greeter, Hello };

Introducing this TS file directly into other TS files not only complements all of the parameter types, but also tells you that you need to fill in a parameter, and that you only have to fill in an object of type person to not give an error. (Intelligent completion and parameter checking)

3. On the refactoring

Dynamic temporary cool, reconstruction crematorium.
Typescript on the advantages of refactoring, we mainly explain from three aspects.

    1. Rename the symbol to make changes to where everything is referenced.
      In VS code if we want to modify the name of a function, variable, or class, we can use the rename symbol function to correctly modify all references in the current project. This can be used in TS or JS, and its underlying implementation is based on TS parser.
    2. Automatically updates the reference path (VS code).
      During refactoring, we may need to move the path of the file, which often leads to an import failure elsewhere, when vs Code provides the ability to automatically update the reference path. Its bottom-up implementation is also based on TS parser.
    3. Check the function signature.
      Sometimes we will refactor the signature of the class or function, if there is a reference to the place forget to change, in addition to the runtime can be found, other times is often difficult to detect, and ESLint can only be troubleshooting simple problems, so the bug will be very troublesome. and TypeScript not the same, in the code can be timely to find where the wrong, where should be changed but not modified.

      [function Signature MDN] [5]

4. Readability

Readability, TypeScript obvious advantage, when viewing open source code, if the comments are not very perfect, tend to look at the foggy, and TypeScript under the same conditions, at least one type, can make it easier to understand the code parameters, return values and intentions.

Preliminary discussion on Ts+vue configuration

Before the formal development, we need to understand some basic configuration.
1.tsconfig.json is a compilation option configuration file for TS projects. In TS projects, if you do not add this file, TS uses the default configuration. Scan the QR code to get the configuration item.

    1. The Ts-loader:webpack typescript Loader is for Webpack to compile the. ts. TSX file.
    2. Tslint:.ts. TSX file code style Checker. (function similar to eslint)
    3. Vue-shim.d.ts: Since TypeScript does not support *.vue suffix files by default, it is necessary to create a vue-shim.d.ts file in the Vue project, which is placed in the project root directory, such as Src/vue-shim.d.ts.
The way to write TS in Vue

The contents of the figure should be written in script lang= "TS".
: Use the base usage of vue.extend.

: Class-based Vue components

By contrast we found that the above coding is closer to our usual JS notation, but we do not feel the type check and type inference of TS.
The following diagram will help us to get the TS type check. This requires us to introduce vue-class-component, although the template can not be complete, but the contents of the script has been better complete. Let's look at the role of Vue-class-component.

Vue-class-component & Vue-property-decorator

The Vue-class-component Enhanced Vue component, which uses the adorner syntax to make the Vue component better for use with TS.
Vue-property-decorator added more Vue-related adorners on vue-class-component, making the Vue component better used with TS.

Both of these are inseparable from adorners, (decorator) adorners are already in the ES proposal. Decorator is the practice of adorner mode. Decorator mode, which is an alternative to the inheritance relationship. Add additional responsibilities dynamically to objects. The performance of the class is enhanced without changing the interface. Let's take Iron Man as an example of how to use ES7 's decorator.

Iron Man, for example, is the essence of Iron Man is a person, just "decorate" a lot of weapons have become so NB, but how to decorate him or a person, it is not changed in nature. Therefore, the adorner does not change its inheritance, but it can also add a lot of powerful skills to it. To put it simply, adorners modify or add members to a class without modifying the inheritance of a class.

Three parameters that the adorner mainly receives:
Target the object on which to define the property.
Key the name of the property to be defined or modified.
Descriptor the property descriptor that will be defined or modified.
Below we have added flight capabilities to a person through our code:

Typescript VS JavaScript

Knowing the basics above, now I'll write the same piece of code using JS and TS, and now we'll compare the differences between them.

    1. Props (Properties)
      Using JS, we have a lot of ways to define the components of the Props, but mostly doped with Vue's private features, and ES incompatible with, such as the left side of the code, obviously we are the object's Prop property is defined as a two string element of the object, However, we can access the "name" field directly from this object, which is obviously non-conforming to ES semantics.
      Take a look at the TS player on the right, mark the specified field with the Prop adorner to Prop, preserving the semantics of the ES syntax, and the perfect fit with Vue, and even better, we can enjoy the static type checking of TS-to-Prop fields during encoding.
    2. Method and data
      Then look at the definition of Method in Method,js or the one we mentioned above that does not conform to ES semantics. In TS, method does not require an additional adorner-the instance approach automatically becomes the algorithm for the Vue component. Similar to data, using the syntax of TS, the instance field can automatically become the data of the Vue component.
    3. Computed
      In the traditional Vue code written with JS, if you want to define a computed property, we need to define the corresponding function in the computed attribute. And this in ES actually already had the grammar--getter of the Chingyi, so in the use of the Vue-class-component Vue component, we can directly use getter to define the computed properties, both syntactically and semantically, compared to ordinary JS All notch above

Summary: We use vue-class-component to make the definition of VUE components more consistent with ES semantics, allowing TS to perform better parsing and type checking based on this.

Use TS + Vue1 in business scenarios. Define data and props in the Vue project

This kind of writing, let me have a two doubts.
1.1 How to use the wording
@Prop (number!:) propa!: Number
Instead of
@Prop (number) Propa:number
1.2 Why does the prop need to write two times before and after the type?

Self-answer link:
Answer 1.1: Because we set a phone this class, no phone, condition these fields are initialized by constructor, so you need to use an explicit assignment assertion on the property to help the type system recognize the type, which allows the property to be indirectly initialized.
Answer 1.2: The type callout in the front bracket is the type check provided by Vue. The colon is followed by the type callout provided for TS.

2. Write a function

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

In the example above, we need to define a type for the OPTs parameter, to facilitate the use of subsequent encodings, and then we need to write an interface to define it as a type. This interface consists of three mandatory attributes and an optional attribute. A property must be assigned when the object is initialized, but sometimes properties in an object can be ignored and not necessarily required. We can set it as an option.

As the business progresses, the fields of some parameters become more and more complex. Maybe you want to have something once and for all, make the interface simpler, and even let it adapt to business changes automatically. So I came up with this code:

The above code: defines a key as string, his value is number or string type of interface, and all the fields of the interface are optional, you can even pass in an empty object. So we can use the above interface can replace the following interface, but the reverse is not possible.

However, we should not go around these checks, because TS will not check for you that the objects that use the interface should have those properties or methods. The significance of using TS is greatly diminished.

3. Preparation of third-party dependencies

In the daily development process, we often encounter problems with the introduction of third-party dependencies into TS projects without type checking, often because they do not provide a type definition file. At this point, we can manually write the type definition file for these third-party libraries, and the type definition files are completely ignored after compilation, so there is no impact on existing code. As an example of the more complex function above, the function is to merge all the fields of all parameters passed into a new object and return it, although his functionality is relatively simple, but it requires some TS techniques to write a type definition for it.
1. External module declaration: First we need to create a file with a. d.ts extension and declare a module in it, declaring the module name to be the same as the path we introduced in the other file.
2. Type parameter-generics: First let's consider the simplest case, when passing in a parameter, the Extend function should return the same object as the parameter type, but we do not know what type of parameter the user will pass when we write the function, so we can define a type parameter T1, Extend is called a generic function, and T1 is also called a generic parameter. In the above example, the Extend function takes a type of T1 parameter and returns a value of type T1, T1 requires the user to pass in manually, fortunately TS is smart enough, in most cases TS can automatically infer the type parameters based on the parameter type, eliminating the tedious steps of our input type parameters. The Extend function, which accepts only one parameter, is not very complex, and we can continue to consider some more complex situations.

This time let's define a extend function that takes three arguments, and it also accepts three generic arguments, and it returns a value type, which is the T1, T2, T3 intersection type. The crossover type allows us to superimpose existing multiple types together into one type, which contains all the types of attributes required, equivalent to the set of members of these types. For example, T1 & T2 & T3 Objects of this type have both members of these three types. In this case, the intersection type satisfies our requirements for the return value type of the Extend function. It is worth noting that the actual extend function can accept an indefinite number of arguments, that is, the type definition that we write for it also needs to be compatible with the case of an indefinite number of parameters, which requires the function overloading functionality provided by TS.
3. Overloading: In most statically typed programming languages, the compiler allows multiple functions of the same name with different number of parameters, which are called function overloads. TS supports function overloading, so we can define multiple extend methods that accept different quantities of parameters, and TS automatically chooses the correct overload definition in those functions with the same name when the user calls. With the help of function overloading, we can enjoy the benefits of type checking in most scenarios using extend, and TS cannot infer the return value type until the number of parameters exceeds 4. Note that in JS, the runtime does not provide the ability to overload functions, we can not define multiple functions with the same name, even if they accept the number of parameters is not the same, in order to achieve the effect of function overloading, developers need to manually in a single function of the parameters of the type, the number of judgments.

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

Personal feelings

Before we explained, using TS in Vue to bring us all kinds of convenience, now in my personal feeling, say the ointment of the place.
1. Even though the use of the Ts,template section does not have static type checking and IDE smart hints, the official members indicate that this feature will be available in a future Vue document.
2. The Vue single file component is introduced into the TS file, and its file location cannot be correctly prompted.
3.Vue peripheral tools, such as VUEX, have weak support for TS, a large number of features that are difficult to migrate directly to TS, and do not have a good official support scheme.
4. Without a doubt, using TS to develop, compared to JS, we need to spend more time and effort.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.