Integrate TypeScript in Vue.js

You may have used TypeScript in the past, or you may be curious about how you can take advantage of the extra tooling TypeScript provides inside of your Vue projects. Why use TypeScript? A recent study found that TypeScript/static typing tools reduced committed bugs by 15%.

What Is TypeScript?

TypeScript is a JavaScript library created by Microsoft. TypeScript is not a new language as it’s still very much JavaScript it’s just another way of writing it. Furthermore, the browser does not understand TypeScript so you need a compiler. So, you will need a compiler or a build step with something like Webpack, Babel, or Parcel.You can use TypeScript as little as you want or as much as you want. It is true, that Vue.js is not heavily reliant on TypeScript; that’s Angular. Angular is so invested in TypeScript, that it’s actually more work for you as a developer to set up and use Angular without TypeScript. You can, of course, use Vue.js with TypeScript (as we will go over soon) but it is not part of the framework, it just enhances it.

 

Using TypeScript With Vue.js

TypeScript has gained popularity over the years. It was first introduced in 2012 and as of 2018, gets about 13 million downloads per month. Again, Angular is really invested in TypeScript, making it it’s primary language in the JavaScript framework. So it has the backing of Microsoft and the full support of Google, two massive technology corporations.

In the past, TypeScript support for Vue.js has been spotty at best. However, with a mixture of community outcry and Core Team dedication, that lack of support is no longer a concern. This is backed up by the fact that Vue CLI 3 now offers a TypeScript option when creating your Vue.js application.

With VUE CLI 3,you can choose the TypeScript option during the creation of your project,or you can add TypeScript to an existing Vue project by the following command:

npm install @vue/cli-plugin-typescript --save

or

yarn add @vue/cli-plugin-typescript

 

With TypeScript for Vue.js, you can use it a few ways. You can either use TypeScript for basic type checking in external files or you can use decorators in your .vue components. Let’s walk through the most basic usage of TypeScript in the Vue project.

With the CLI plugin installed, we can now import external files or extract functions from said files into the components. This can easily be done by creating a .ts file. These .ts files will commonly go into the assets directory or new ts directory in the src folder.

ts/utilities.ts

export function consoleMe(message: string): void 
{
console.log(message);
}

 

In this example, we have a simple function called consoleMe that accepts a string, console logs a message, and returns the type of void or...nothing.

Let’s import this function into the App.vue component and run it on the mounted lifecycle method.

App.vue

 

<script> 
import { consoleMe } from '@/ts/utilities';

export default {
mounted()
{ consoleMe("You don't need to define a language in your script tag to use TypeScript like this!");
}
}
</script>

 

In the example above, we don’t need to define either a file extension for utilities.ts or a language (lang="ts") in the <script> tag. When you start to write out the function, consoleMe, your text editor should show you what the function accepts and returns.

When building the project, the TypeScript compiler will compile your external code and ensure the external functions are accepting and returning the proper types. You can run the Vue.js project with:

$ npm run serve # or $ yarn serve

 

Try changing the string to a different data type like a number. When you build the project, the build will fail and an error will display in your terminal window.

In addition to external files, you can also use TypeScript as the language in your Vue component, with a few differences.

To use TypeScript in your component, you must first declare the Vue to use TypeScript with the langattribute.

<script lang="ts"> </script>

 

Another noticeable difference is the export statement. Exporting the component is not as straightforward as it is traditionally. When using TypeScript you must always import the Vue library and extend the library when exporting it.

Traditional Vue.js

 

<script> 
export default {
...
}
</script>

 

Component with TypeScript

 

<script lang="ts"> 
import Vue from 'vue';
export default Vue.extend({
...
});
</script>

 

After doing that, you can now annotate your components methodscomputed properties, and watch properties as if you were annotating functions in your external .ts files.

<script lang="ts"> 

import Vue from 'vue';

export default Vue.extend({

methods:

{ getFirstName(): string { return user.name; } },

mounted()

{ console.log('Component is mounted!'); } });

</script>

 

Using Class-Style Components With Decorators

The class-based style is completely optional. However, if you prefer this style, Vue.js has great support for TypeScript decorators through their vue-class-component decorator package; officially maintained by the Vue.js Core Team.

Using the class-based style is easier than ever to get started. When initializing your project with Vue CLI 3  be sure to check the “TypeScript” option. The CLI will ask, “Use class-style component syntax?”, be sure to type “y” or “yes”. Vue CLI 3 will download and install the vue-class-component and vue-property-decorator packages in addition to the main TypeScript library.

If you did not opt in for the class-style syntax when creating your Vue.js project, don’t worry. You can install it with the following commands

$ npm install @vue/cli-plugin-typescript --save-dev 
$ npm install vue-class-component --save-dev
$ npm install vue-property-decorator --save-dev
or

$ yarn add @vue/cli-plugin-typescript
$ yarn add vue-class-component
$ yarn add vue-property-decorator
# __Note:__ You can also install all of these with one command.

 

When installed (or initialized) you’ll notice that when using classes, the syntax is different than a traditional Vue.js application. If you are not used to TypeScript or are very familiar with the Vue.js syntax to date, this may be a little intimidating. When using the class-based syntax, you use “decorators” in you’re Vue.js component; there are a total of eight (8) decorators:

  • @Emit
  • @Inject
  • @Mixins (the helper function named mixins defined at vue-class-component)
  • @Model
  • @Prop
  • @Provide
  • @Watch
  • @Component (from vue-class-component)

 

let’s compare and contrast the traditional component syntax with the class-style syntax.

Traditional

 

<script> 
import someComponent from '@/components/SomeComponent';
export default {
name: 'MyComponent',
props: { name: { type: String, } },
data() {
return { location: 'Cincinnati, OH', }
},
methods: {
someMethod() {
// Do something } },
computed: {
someComputedProperty() { return foo; }
},
mounted()
{
console.log('component is mounted!);
}

};
</script>

 

Class Style Syntax

 

<script lang="ts">

import { Vue, Component, Prop } from 'vue-property-decorator';
import someComponent from '@/components/SomeComponent';

@Component({
components: { SomeComponent, },
});

export default class MyComponent extends Vue {
// Props
@Prop(String) name!: string;
// Data
location: string = 'Cincinnati, OH';
// Methods
someMethod()
{ // Do something
}
// Computed Properties 
someComputedProperty()
{ return foo; }
// Lifecycle Methods
mounted()
{
console.log('The component is mounted!');
} };

</script>

 

As you can see, the class-based syntax (for the most part) actually has less code than the traditional syntax. With the class-based syntax, your component’s methods, computed properties, data properties, and more are not wrapped in objects. Instead, they’re listed as functions and variables. You can see that with the class-based syntax, you can actually get a lot more done in your components while keeping the line length at a minimum.

You can, of course, annotate your methods and computed properties and take advantage of all of the TypeScript features like interfaces and classes.

Conclusion

TypeScript is a popular choice for type checking your JavaScript code. There are other options to consider, like Flow (Facebook), but the TypeScript community is much larger and active. Along with the support of Microsoft, TypeScript has proven to be a viable technology to add to your current stack with support from the three mainstream frameworks.

Tags :