Starting a TypeScript project with Visual Studio Code

Visual Studio Code is a very great IDE for TypeScript. While VS Code is a lightweight source editor, it is very powerful. It supports lots of languages such as C++, C#, Java, Python, PHP, Go, but some of them have a better integration. This is the case for TypeScript. VS Code allows you to write TypeScript code with autocompletion, refactoring, error reporting, quick fixes, automatic build, debugging, etc. In this post, we'll see how to set up your first TypeScript project with VS Code.

If you are not familiar with VS Code, here's a quick description from the documentation:

Install Visual Studio Code and TypeScript

  1. Install VS Code: https://code.visualstudio.com/

  1. Install NodeJS : https://nodejs.org/
  2. Install TypeScript using the following command line:
npm install -g typescript
  1. Check TypeScript is installed
tsc --version

Create a project

  1. Create a new folder that will contains the sources
  2. Create a tsconfig.json with the following content (you can use the command tsc --init):
{
    "compilerOptions": {
        "target": "es5"
    }
}
  1. Create an src folder
  2. Add an empty TypeScript file in the src folder

The file structure should be like:

MyTypeScriptProject
├── src
│   └── main.ts
└── tsconfig.json

Compile the project

Open the command palette using CTRL+SHIFT+P, and type "Tasks":

Select "Configure Default Build Task", then select "tsc:watch"

This will create a new file .vscode/tasks.json with the following content:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "option": "watch",
            "problemMatcher": [
                "$tsc-watch"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

You can now build your TypeScript files by pressing CTRL+SHIFT+B. After the compilation succeed, you should see a new file main.js in the explorer:

The task is a watch task, so TypeScript will run automatically when you change a TypeScript file.

Hide the JavaScript file from the Explorer

After compiling the TypeScript files, you'll have lots of ts and js files in the explorer of VS Code. As you'll never edit the JS files, you can simply hide them in the Explorer.

  1. Open the settings: File -> Preferences -> Settings
  2. Select "Workspace settings" in the right panel
  3. Add the following json
{
    "files.exclude": {
        "**/*.js": true
    }
}

The workspace settings are saved in .vscode/settings.json, so this will apply only for the current project.

Conclusion

You are now ready to use Visual Studio Code for your TypeScript projects