“Mastering TypeScript: Best Practices for Developers”

Vaishnavi Neema
2 min readNov 6, 2023

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.

Install the TypeScript compiler

Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc. You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript (tsc HelloWorld.ts).

The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally (-g) on your computer by:

npm install -g typescript

You can test your install by checking the version.

tsc --version

Hello World

Let’s start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.

mkdir HelloWorld
cd HelloWorld
code .

Now add the following TypeScript code. You’ll notice the TypeScript keyword let and the string type declaration.

let message: string = 'Hello World';
console.log(message);

To compile your TypeScript code, you can open the Integrated Terminal (⌃`) and type tsc helloworld.ts. This will compile and create a new helloworld.js JavaScript file.

If you have Node.js installed, you can run node helloworld.js.

If you open helloworld.js, you'll see that it doesn't look very different from helloworld.ts. The type information has been removed and let is now var.

var message = 'Hello World';
console.log(message);

tsconfig.json

You can modify the TypeScript compiler options by adding a tsconfig.json file that defines the TypeScript project settings such as the compiler options and the files that should be included.

Important: To use tsconfig.json for the rest of this tutorial, invoke tsc without input files. The TypeScript compiler knows to look at your tsconfig.json for project settings and compiler options.

Add a simple tsconfig.json that set the options to compile to ES5 and use CommonJS modules.

{
"compilerOptions": {
"target": "es5",
"module": "commonjs"
}
}

By default, TypeScript includes all the .ts files in the current folder and subfolders if the files attribute isn't included, so we don't need to list helloworld.ts explicitly.

You’ve likely not set "sourceMap": true in your tsconfig.json and the VS Code Node.js debugger can't map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.

--

--