Getting Started with Typescript in VS Code

TypeScript is Microsoft's relatively new programming language which is essentially JavaScript, but with types. Not only does it provide static type checking, it allows you to use modern and even future features that will come to plain JavaScript. TypeScript adoption is starting to take off and now being used in production systems. In fact, Angular, a very popular client-side framework, is now written in TypeScript. Today, there are a plethora of IDEs that support TypeScript. But my personal IDE of choice when working with client-side stuff is Visual Studio Code. In this post, I will walk you through the steps on getting started with TypeScript in Visual Studio Code!

Installing Typescript

We need to install Typescript before anything else. Go to Typescript's official website. Typescript is supported across a myriad of IDE's either built-in or via plugins or extensions. Depending on what IDE you will use, download the appropriate installer. For this post, I will be using Visual Studio Code.

Installing Visual Studio Code

I prefer using Visual Studio Code (or simply VS Code) when coding in Typescript, Javascript, or any frontend web development since it's lightweight and focused more on the actual code. It can be run not only on Windows but on Mac and Linux environments as well. It has more code-focused features than the full Visual Studio and those should probably be a good topic for a separate post. Oh, and did I mention it's free? I'll be using VS Code to demonstrate Typescript's capabilities. Proceed to Visual Studio Code's official website and download the installer. Follow the simple installation wizard to install VS Code.

Installing Typescript via Node

Even if Visual Studio Code already has its built-in Typescript distribution, it would be nice if we can compile TypeScript files in the command prompt. I hope you have Node installed as typescript is installed globally via Node's NPM (Node Package Manager). Install TypeScript by running the following command in the command prompt.

npm install -g typescript

You can verify if Typescript is installed properly using the following command:

tsc --version

At the time of this writing, the version I am using is 2.2.1.

New Project

I'll show you how easy it is to create a new project in VS Code. Type the following command in the command prompt.

mkdir TypescriptExample001
cd TypescriptExample001
code .

The first command creates an empty directory named TypescriptExample001 and you can replace this name with whatever you want. The second line navigates inside that newly created folder. The third one is a command to open VS Code. The period is a parameter meaning that open VS Code in the current directory. VS Code should now open and you should see that you are inside the folder you just created. You can look at the Explorer or just the title bar to confirm. You have essentially created a new project in VS Code. VS Code works with directories and you can just open any directories and add new files to it. You don't need any project files like .csproj and .sln to work with VS Code.

Hello World in TypesScript

To add a TypeScript file, click the New File icon in VS Code's Explorer.

VS Code New File

A TypeScript file has a file extension of .ts so name the file app.ts and add this single line of code.

console.log("Hello World");

Wait, isn't this just a simple JavaScript line to output something in the console? Yes! As I have said in the beginning, TypeScript is just JavaScript... with types. You can code or copy/paste any JavaScirpt in a TypeScript file and it is perfectly valid (with some exceptions based on how you configure Typescript).

Transpiling From TypeScript to JavaScript

Browsers understand JavaScript, not TypeScript. When developing in TypeScript, part of the workflow is to compile it into JavaScript that will be understood by browsers or any JavaScript environment (like Node). Actually, a more accepted term is transpile than compile. Transpilation is the process of converting one language to another. Transpilation in TypeScript can be done by issuing the following command in the command line (be sure you are in the same folder as the TypeScript file you are transpiling):

tsc app.ts

You can even do this in VS Code without leaving the IDE. Press Ctrl + ` (that's Ctrl and backtick) to open the VS Code's integrated terminal. There, you can just type the same command above. After you execute the command, see a file named app.js magically appear in your Explorer. The contents of this transpiled JavaScript file is exactly similar to our original TypeScript file. This is because we didn't write any TypeScript-specific features yet. Before we dig in with TypeScript features, we need to first learn about tsconfig.json.

Configuring TypeScript with tsconfig.json

When you simply run tsc without any parameters, it will ask for several parameters that it needs to properly do its job. We've seen an example in the previous section where we supply the name of the TypeScript file to transpile. There are more options you can set to control how TypeScript transpiles your JavaScript files. This can be controlled by creating a JSON file named tsconfig.json on the same folder where you will run the tsc command which is typically the root of your project.

You can either create the tsconfig.json file manually, or you can use one of tsc command switches --init. Go to VS Code's terminal again and type the following command:

tsc --init

That's it! You should see a tsconfig.js file created in VS Code's explorer. By default, it contains the following:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    }
}

I won't be digging into much detail as to what these properties do but another feature of VS Code is that you can simply hover on each of these properties and see a brief description of their purpose. Since we're here, I would like you to add some non-default properties to this tsconfig.js. First, let's add the outDir property with a value of "dist". This indicates where our transpiled JavaScript code will be placed instead of just placing them on the same directory as their TypeScript counterpart. This allows as to easily distribute our transpiled JavaScript code and you can simply add the whole dist folder in your .gitignore file so it won't be committed in Git if you are using it. If you want TypeScript to automatically recompile your changes when you save a TypeScript file, you can set the watch property to true. Your new tsconfig file should look like:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false,
        "outDir": "dist",
        "watch": true
    }
}

Now that we have our tsconfig.json, all you have to do is type tsc in VS Code's terminal without any parameters. It will automatically recognize tsconfig.json by name and read its content. Since we set watch to true, any change we do in our TypeScript files should automatically be transpiled. Notice that the transpiled JavaScript files are now located under the dist folder thanks to the outDir property.

Running TypesScript in VS Code

Typically, you would create a web page and reference the generated JavaScript file from there, but we will do something different here. When I started learning my first programming language, all I have is a console application that outputs Hello World. Since we are just concerned with learning TypeScript as a language, not as a tool to manipulate DOM elements in the browser, we will run our code entirely in VS Code and use its integrated Debug Console window. After all, JavaScript is no longer just exclusive to browsers. You can use JavaScript today to create back-end systems using Node, mobile apps using Ionic or NativeScript, or even desktop applications using Electron.

First, we need to setup VS Code to run our JavaScript file. Press Ctrl + Shift + P to open a dialog that allows you to search all available commands in VS Code. Search for the word launch and you should see a result named Debug: Open launch.json. VS Code Launch.json

By clicking that, you will be asked to choose an environment. VS Code runs JavaScript files via Node so chose Node.js. It will then create a launch.json file under the .vscode folder and you can see it in VS Code's Explorer. Open launch.json and change the value of program to "${workspaceRoot}/dist/app.js" and outFiles to [ "${workspaceRoot}/dist/**/*.js" ]. Your launch.json should look like this:

{
    // Use IntelliSense to learn about possible Node.js debug attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/dist/app.js",
            "cwd": "${workspaceRoot}",
            "outFiles": [ "${workspaceRoot}/dist/**/*.js" ]
        },
        {
            "type": "node",
            "request": "attach",
            "name": "Attach to Process",
            "port": 5858,
            "outFiles": []
        }
    ]
}

Let me explain a little bit the contents of this file. VS Code can have multiple ways of running an application and they are called launch configurations represented by an array of objects inside the configurations property. I'll be creating a separate post for debugging in VS Code so I will be skipping most of the properties here. The important properties, for now, are program and outFiles. The program property tells VS Code what file will be the entry point. This is similar to the Main method in many C-like languages like C#. Here we set it to the dist/app.js which is the JavaScript equivalent of our main TypeScript file app.ts. outFiles indicates which files to include when running the application. Since we indicate in our tsconfig.json file that our transpiled JavaScript will be outputted to the dist folder, we specify a glob pattern which instructs VS Code to include all JavaScript files under the dist folder or within any subdirectories. ${workspaceRoot} is simply a predefined variable pointing to the root folder.

Everything is now ready and we can run our application. Press F5 to run and put VS Code in debug mode. Go to Debug Console and indeed, we see the Hello World message.

Debug Console in VS Code

To stop debugging, click on the stop icon in the Debugging Toolbar or hit Shift + F5.

Debugging Toolbar

Our First Real TypeScript application

Currently, our program is really just plain JavaScript that calls the console to log a message. Here's an actual TypeScript code having TypeScript specific features.

class Greeter {

    constructor(private greeting: string, private name: string) {
    }

    greet () {
        console.log(`${this.greeting}, ${this.name}!`);
    }
}

var greeter: Greeter = new Greeter('Hello', 'TypeScript');

greeter.greet();

Run the program again by pressing F5 and you will see Hello, TypeScript! as the output!

You can download the final code from this GitHub repository: https://git.io/vyOMO