Typescript

Typescript

Typescript is a superset on top of Javascript, extending it by adding a type system.

Type checking occurs within the IDE (if configured) and at compile time.

Typescript must be compiled to Javascript to be used in a browser.

Installation

Add Typescript to an existing Vue project with vue add typescript and choosing these options

? Use class-style component syntax? No

? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes

? Convert all .js files to .ts? No

? Allow .js files to be compiled? Yes

This adds @vue/cli-plugin-typescript which adds the necessary webpack-chain rules to compile typescript.

Usage

Files can be ‘converted’ to Typescript by simply changing the extension to .ts (in the case of a vanilla Javascript file) or changing the script tag to <script lang="ts"> in a Vue Single File Component.

Expect a lot of type errors after doing this, as no type assignments will be in place.

Configuration

The typescript compiler’s configuration is found in tsconfig.json at the project root.

By default, the compiler will print errors, but not prevent compilation if they are encountered. This is helpful while migrating existing JS code to TS, as it allows you to incrementally add type assignments.

To change this behaviour, set noEmitOnError: true within tsconfig.json.

General use

It’s recommended to use Typescript wherever possible. New code should be written in Typescript unless there’s a really pressing reason not to. Existing code should be migrated over to Typescript. If a new feature is being implemented in an existing Javascript module, write the new feature in Typescript, and consider migrating the whole module at the same time.

Use with Vue

Vue ships with official type declarations. Vue3 has been re-written from the ground up entirely in Typescript.

Use with Vuetify

Vuetify is written in TypeScript and has type definitions compatible with Typescript 3.9.