How Typescript integrated with Vue.Js

A few weeks ago, I started a new Vue project. One of my co-developers recommend the use of TypeScript on the project: "It will help us find mistakes and errors, and the sooner we add, the easier it is." This is my first time using TypeScript development. "

Why TypeScript?

TypeScript Home: https://www.typescriptlang.org/index.html

// The variable x will be seen as a boolean
let x: boolean

// Here the type inference makes y as a boolean too
let y = true

You can type variables, function parameters, the function will return ... TypeScript then your code static analysis to check for dangerous operation (depending on the type). You might accidentally try to assign the wrong attribute type or object to access an undefined variable. The last question in the event of a lot of running, you do not have to check whether the object is not null. The code then collapsed ......

let x: boolean

/**
If you want to assign another a value with the wrong type
TypeScript will trigger an error. In my editor I have :
Assigned expression type "This is a string, not a bool" is not assignable to type boolean
**/
x = 'This is a string, not a bool'


/**
Here 'find' can return undefined if no correct document is found.
Therefore, accessing the property 'type' will trigger a runtime error
**/
const documents = [{type: 'Review'}, {type: 'Book'}]
const myArticle = documents.find(document => (document.type === 'Article'))

const myArticleType = myArticle.type

For the last example, the following error in the compilation process:

TypeScript strict null check error

I hope this will convince you to use TypeScript. If you are a beginner, I recommend that you read the manual

Now let's see how to install it in Vue project.
Use TypeScript in Vue in
a new project on installation TypeScript

If you start a new project, you can use the Vue CLI make their own settings, then select Typescript the options.

How Typescript integrated with Vue.Js

Then enter "yes" to the use of components of grammar class style. We'll explain why you should use this syntax.

How Typescript integrated with Vue.Js

On existing projects

If you add it to an existing project, you can still use the NPM add TypeScript:

npm install -g typescript

Also, you can check the recommended configuration TypeScript configuration.

TypeScript use in Vue code syntax

First, let us tell our Vue compiler, Javascript will be TypeScript. In the script tag Vue file, do the following:

<template>
</template>

<!--Add lang="ts" to specify it's TypeScript-->
<script lang="ts">
</script>

<style>
</style>

Then, we need to modify the grammar TypeScript friendly.

During the installation (by Vue CLI), I recommend that you use the component class style of syntax. But there are other syntax. In the Vue, there are three kinds of syntax: Options API, Composition API and Class API. I recommend that you use the latter. However, we will see how to TypeScript used in conjunction with them.

Options API

This syntax is the basic syntax of Vue. But you need to export the components in different ways. Export is not enabled usual type inference:

<template>
</template>

<script lang="ts">
export default {
  //No type inference
  components: {},
  data() { return {} },
  computed: {},
  created() {},
  methods: {}
}
</script>

<style>
</style>

Therefore, you will need to use Vue.extend syntax export Javascript:

<template>
</template>

<script>
import Vue from 'vue';

// Note the Vue.extend
export default Vue.extend({
  //Type inference
  components: {},
  data() { return {} },
  computed: {},
  created() {},
  methods: {}
})
</script>

<style>
</style>

When I began the project, we use options API in Vue file. But we encountered some problems in terms of TypeScript, it was decided to use Class API. Frankly, in hindsight, I think some of the problems because we are not used correctly TypeScript together with the option to use API. For example, do not type the function returns. Now, with the latest update TypeScript, I am no longer able to reproduce these errors.

But I still recommend that you use class style components for encoding, because you might like me on the Options API encountered some minor problems. In addition, there are more exemplary network with class style assembly.

Composition API

The syntax is the new syntax Vue 3. The syntax is considered TypeScript integrated in the building. Therefore, Composition API will provide better TypeScript support, and I think that you do not have to use TypeScript and change the syntax. If you are using this syntax in Vue 2, you can use composition-api package. Vue 3 will be released in early 2020, it is currently in the (pre) Alpha version. If you have time to study this new syntax, we recommend that you start using it to encode to become familiar with Vue 3.

However, if you want to wait before using the composition API released, please see the syntax finally available.

Class API

The main purpose of the introduction of class API is to provide a better TypeScript reasoning to support alternative API.

To use the Class API syntax, you will need to install the package vue-class-component (already installed with Vue CLI).

Then create Vue component uses the following syntax:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  props: {
    myProp: {
      type: String
    }
  }
})
export default class HelloWorld extends Vue {
  myData: {name: string} = {name: 'test'}

  // computed are declared with get before a function
  get myComputed(): string {
    return this.myData.name
  }

  created() {}

  // methods are just functions
  myMethod(): boolean {
    return false
  }
}

You will soon get used to the syntax!

One advantage of this syntax, you can press the function regroup 'methods' and 'computed' (composition API also built for that purpose).

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({})
export default class HelloWorld extends Vue {
  // Autocomplete functionality
  get computedRelatedToAutocomplete() {
    ...
  }
  methodRelatedToAutocomplete() {
    ...
  }

  // Search Functionality
  get computedRelatedToSearch() {
  ...
  }
  methodRelatedToSearch() {
  ...
  }
}

Vue 2 full support package vue-class-component.

We can do another improvement is to use a software package vue-property-decorator. The package is also installed by Vue CLI.

With it, even the props will also be within the definition of the components:

import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class HelloWorld extends Vue {
  // The props are defined here with the annotation @Prop()
  @Prop()
  private msg!: string;

  myData: {name: string} = {name: 'test'}

  // computed are declared with get before a function
  get myComputed(): string {
    return this.myData.name
  }

  // methods are just functions
  myMethod(): boolean {
    return false
  }
}

Drawback: Class API is still not a perfect match with TypeScript, Composition API will be replaced by the Vue 3 in. After Vue 3 release, I strongly recommend that you use Composition API.

But for now, this is our best solution! Changing from one representation to another representation is not so complicated. You can change the file one at a time, while still using another syntax to run other files. That's what we like to change from the options API API changes. Even today, we still have the old files with the option API syntax (we are gradually migrating).

In fact, you can use the Vue achieve TypeScript (If you add it to an existing project) a file at the same time. You get a Vue file, and then add lang = "ts" in the script tag. Then, modify the components to use Class API and fix potential errors TypeScript found. Really simple!

Tips and tricks

Enter the props in the Vue

In your project, you will want to type props. Indeed, the type that you define as a prop should be a Vue types. You can use Boolean values, strings, arrays, but you can not use home-made type.

Import View from 'view';

type MySuperType = {
  name: string
  age: number
}

export default Vue.extend({
  props: {
    mySuperProps: {
      type: MySuperType, // Will not work
      required: true
    }
  }
})

You will need to use another syntax:

Import View from 'view';

type MySuperType = {
  name: string
  age: number
}

export default Vue.extend({
  props: {
    mySuperProps: {
      type: Object as () => MySuperType,
      required: true
    }
  }
})

Typescript in use in Vuex

If you plan to use Vuex in the project, you can also enter the store. In this article Vuex and TypeScript, you will find detailed instructions on how to type and how to store actions within Class API using the component / state / acquirer of.

Access attribute may be empty object

Sometimes you will have an empty object. Prior to access an object property, you need to check whether the object is not null. But you can not carry out this check anywhere. It must be close access to the property.

Here are some examples of empty objects / tips:

import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class HelloWorld extends Vue {
  value: null | {test: string} = null
  setValue() {
    this.value = {test: 'hello'}
  }

  /**
  * this.value can be null,
  * we cannot access the property test on null
  *
  * An error will be triggered
  */
  methodWithTypeError() {
    this.value.test //error
  }

  /**
  * checking that value is not null before accessing property
  * will tell TypeScript that the variable is safe
  *
  * No error will be triggered
  */
  methodWithNoError() {
    if(this.value === null) {
      return
    }
    this.value.test
  }

  /**
  * When performing its analysis TypeScript will not check the whole code
  * Therefore, even if we have checked this.value before
  * it will still see it as null inside the map function
  *
  * An error will be triggered
  */
  methodWithErrorWhereItShouldBeOK() {
    {
      if(this.value === null) {
        return
      }
      const array = [1, 2, 3]
      array.map((arrayValue: number) => {
        return arrayValue + this.value.test //error
      })
    }
  }

  /**
  * Here by assigning this.value.test to
  * another variable just after the null test,
  * TypeScript will infer its type as not null
  *
  * No error will be triggered
  */
  fix() {
    {
      if(this.value === null) {
        return
      }
      let test = this.value.test
      const array = [1, 2, 3]
      array.map((arrayValue: number) => {
        return arrayValue + test
      })
    }
  }
}

How Typescript integrated with Vue.Js

Another solution to this problem is to use lodash function get, if the object is null, the default value is returned. However, using this solution, you do not need to use TypeScript when accessing properties.

It took me some time to get used TypeScript. At first, I did not understand the full functionality of TypeScript, and that this is extra work. But as time went by, I became accustomed to TypeScript, and my Javascript code more structured. Now, it is easier to develop, especially when encoding with other developers: TypeScript allows you to target given shape, so that other objects easier to understand.

I hope this will convince you to use TypeScript, and for your help.

Guess you like

Origin www.linuxidc.com/Linux/2019-11/161514.htm