Working with TypeScript in Visual Studio Code

Publikováno: 19.2.2019

TypeScript and Visual Studio Code are two amazing products created by Microsoft, and - surprise surprise- they work amazing together! Let's take a look at how Visual Studio Code makes it a breeze t...

Celý článek

TypeScript and Visual Studio Code are two amazing products created by Microsoft, and - surprise surprise- they work amazing together! Let's take a look at how Visual Studio Code makes it a breeze to work with and configure TypeScript!

TLDR

Install the TypeScript package globally and create a ".ts" file to get started. Visual Studio Code gives live TypeScript feedback to help you write better code, and provides intellisense when creating TypeScript configurations.

What is TypeScript

To be honest, JavaScript made me really uncomfortable for a while. Coming from a background in C# and Java, the lack of strong typing terrified me. The thought that I could pass anything to a function regardless of what it expected didn't feel right.

In comes TypeScript, a typed superset of JavaScript that compiles to plain JavaScript. Ok, a couple of key words here.

  • 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.

TypeScript was created by Microsoft, who also created Visual Studio Code. As you might expect, they work pretty well together! Let's take a look.

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.

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 welcomePerosn function. I could pass nothing, a string, etc. literally anything I want. In TypeScript, we can create interfaces which 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 (and VS Code is awesome!), VS Code will immediately provide you feedback letting you know that the function expects a Person object and not a string.

VS Code understands TypeScript in and out and is ready to help you improve your code and prevent errors.

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.

If you didn't fix the error before, you'll see any error 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.

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

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).

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

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 simple 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.

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

For funsies, try deleting "outDir", and then start typing it in again. Did you notice that VS Code is providing you intellisense for which properties you can set in a TypeScript config file?! How cool is that?!

VS Code provides intellisense for TypeScript config properties.

I changed my out directory to a dist folder like so.

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

TypeScript in Use

TypeScript has gained more and more popularity over the last couple of years, and I think it will continue to do so. Here's a couple of examples of how they are used in modern front-end frameworks.

Angular CLI

https://cli.angular.io/

Angular CLI projects come preconfigured with TypeScript. All of the configuration, linting, etc. is built in by default, which is pretty sweet! 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 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

Vue CLI projects can be configured to use TypeScript when creating a new project. For more details, you can check out the [Vue Docs](https://vuejs.org/v2/guide/typescript.html).

Recap

TypeScript is awesome! It allows you to generate higher quality JavaScript that can you feel more comfortable about when shipping to production. As you can tell, VS Code is excited and well equipt to helping you write TypeScript, generating configurations, etc.

If you haven't already, give TypeScript a try. Let us know in the comments below what you think!

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace