While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

TypeScript and Visual Studio Code are products created by Microsoft. In this tutorial let’s work with TypeScript in Visual Studio Code.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

  • typed - You can define variable, parameter, and return data types.
  • superset - TypeScript adds some additional features on top of JavaScript. All valid JavaScript is valid TypeScript, but not the other way around.
  • compiles to plain JavaScript - TypeScript cannot be run by the browser. So available tooling takes care of compiling your TypeScript to JavaScript for the browser to understand.

Installing and Compiling TypeScript

The first step toward working with TypeScript is to install the package globally on your computer. Install typescript package globally by running the following command.

  • npm install -g typescript

Now, we need to create a new TypeScript file. For reference, these end with the file type .ts. I’ll then start my file with an export for VS Code to think of it as a module.

For now, you can add any valid JavaScript, but I’m going to start by creating a function that will print the first and last name from a person object. We’ll build on this in a second.

export {};

function welcomePerson(person) {
  console.log(`Hey ${person.firstName} ${person.lastName}`);
  return `Hey ${person.firstName} ${person.lastName}`;
}

const james = {
  firstName: "James",
  lastName: "Quick"
};

welcomePerson(james);

The problem with the code above is that there is no restriction on what can be passed to the welcomePerson function. In TypeScript, we can create interfaces that define what properties an object should have.

In the snippet below, I created an interface for a Person object with two properties, firstName and lastName. Then, mark the welcomePerson function to accept only person objects.

export {};

function welcomePerson(person: Person) {
  console.log(`Hey ${person.firstName} ${person.lastName}`);
  return `Hey ${person.firstName} ${person.lastName}`;
}

const james = {
  firstName: "James",
  lastName: "Quick"
};

welcomePerson(james);

interface Person {
  firstName: string;
  lastName: string;
}

The benefit of this will become clear if you try to pass a string into that function. Because we are working with a TypeScript file, VS Code will immediately provide you feedback letting you know that the function expects a Person object and not a string.

The code from the previous block in VS Code

Now that we have a working TypeScript file, we can compile it to JavaScript. To do this you simply need to call the function and tell it which file to compile as shown in the screenshot. I’m using the built in terminal in VS Code for reference.

calling the file with `tsc app.ts`

If you didn’t fix the error before, you’ll see any error output.

error in the output

Fix the error by passing the person object in correctly instead of a string. Then compile again, and you’ll get a valid JavaScript file.

Notice that the template literal strings, which are an ES6 feature, were compiled simple string concatenation from ES5. We’ll come back to this shortly.

compiled JavaScript

Just to prove this worked. You can now run the JavaScript directly using Node, and you should see a name printed to the console.

running the JavaScript using `node app.js` and receiving the output `Hey James Quick`

Creating a TypeScript Config File

So far, we’ve compiled one file directly. This is great, but in a real world project, you might want to customize how files are compiled. For instance, you might want to have them be compiled to ES6 instead of ES5. To do this, you need to create a TypeScript configuration file.

To create a TypeScript configuration file, you can run the following command (similar to an npm init).

running tsc --init with the output that tsconfig created

Open your new config file, and you’ll see lots of different options, most of which are commented out.

options listed and commented out in the new config file

You might have noticed there is a setting called “target” which is set to “es5”. Change that setting to “es6”. Since we have a TypeScript config file in our project, to compile you need to run “tsc”. Go ahead and compile.

Now open up the newly created JavaScript file. In the output, notice that our template literal string was left alone, proving that our TypeScript was compiled successfully to ES6.

The compiled file

Another thing we can change is where our JavaScript files are stored after being created. This setting is “outDir”.

Try deleting “outDir”, and then start typing it in again. VS Code is providing you intellisense for which properties you can set in a TypeScript config file.

Showing intellisense working

We can change our out directory to a dist folder like so.

Changing the out directory to a dist

After compiling again, notice that my output JavaScript file is indeed located inside of a “dist” folder.

Folder directory under dist

TypeScript in Use

TypeScript has gained more and more popularity over the last couple of years. Here’s a couple of examples of how it is used in modern front-end frameworks.

Angular CLI

Angular CLI homepage

Angular CLI projects come preconfigured with TypeScript. All of the configuration, linting, etc. is built in by default. Create an Angular CLI project and take a look around. This is a great way to see what TypeScript looks like in a real app.

Create React App 2

Create React Ap 2 on the Scotch website
Create React App doesn’t come with TypeScript by default, but with the latest version, it can be configured that way. If you’re interested in learning how to use TypeScript with Create React App, check out this article, [Using Create React App v2 and TypeScript](https://scotch.io/tutorials/using-create-react-app-v2-and-typescript)

Vue CLI 3

Project Creation page with Vue CLI 3

Vue CLI projects can be configured to use TypeScript when creating a new project. For more details, you can check out the Vue Docs.

Conclusion

TypeScript allows you to generate higher quality JavaScript that can provide more confidence when shipping to production. As you can tell, VS Code is excited and well equipped to help you write TypeScript, generating configurations, and so on.

0 Comments

Creative Commons License