How to use TypeScript in Visual Studio Code

We can write TypeScript code on VS Code. It doesn’t come with the compiler. We need to install it globally before using it in VS Code. In this post, I will show you how we can use typescript in visual studio code and a few of its useful features like error checking, IntelliSense, etc.

Install typescript :

Visual studio code doesn’t come with the typescript compiler. You need to install it globally on your system. If you have npm installed, just run the below command to install it globally :

npm install -g typescript

Once it is completed, you can verify the installed version by running tsc —version command on a terminal. If the installation is done, you can use it with visual studio code.

Running your first typescript program on VS Code :

Create one new folder and create one file hello.ts in it. Open this folder in Visual studio code and add the below code in the hello.ts file :

function printNumber(n: number){
    console.log(`number is ${n}`)
    return 
}

printNumber(2)

Now, on the terminal window, run the below command :

tsc hello.ts

It will not print the console.log output but one new javascript file hello.js will be created on the same file.

This file holds the actual javascript code :

function printNumber(n) {
    console.log("number is " + n);
    return;
}
printNumber(2);

Now, run node hello.js and it will print the console output.

TypeScript VScode example

IntelliSense :

VS code provides code completion, suggestion, syntax highlighting and bracket matching. e.g. you are typing any object name, it will automatically show the available method names for that object. You can also see the method details if you hover over any method name.

TypeScript VScode example

Errors :

Typescript can automatically show errors by checking the types. VS Code can automatically show you the errors by underlining it with a red line.

TypeScript VScode example

It also shows other compile time warnings. In the above example image, the number 2 is underlined with a red line as its type is mismatching. Also, the second console.log is underlined with a green line because this line is not reachable.