How to Set Up a TypeScript Project in Visual Studio Code

A beginner-friendly guide to creating and running a TypeScript project using Visual Studio Code.

TypeScript is a popular programming language that builds on JavaScript by adding type safety and modern features. Visual Studio Code (VS Code) is a widely used code editor that provides great support for TypeScript. This tutorial will guide you step-by-step to set up a TypeScript project in VS Code.

First, you need to have Node.js installed on your computer because TypeScript runs on Node's ecosystem. You can download it from nodejs.org. Once it's installed, open your terminal or command prompt to install TypeScript globally by running the command `npm install -g typescript`. This makes the TypeScript compiler (tsc) available anywhere on your system.

Next, create a new folder for your project and open it in VS Code. Initialize a new npm project by running `npm init -y` in the terminal inside your project folder. This creates a package.json file which manages your project dependencies.

Now, install TypeScript locally in your project with the following command: `npm install typescript --save-dev`. It’s recommended to have a local version to avoid compatibility issues.

You need a TypeScript configuration file (tsconfig.json) to specify how TypeScript compiles your code. Run `npx tsc --init` in the terminal. This command generates a tsconfig.json file with many options. The default settings work fine for beginners.

Let’s create a simple TypeScript file. Create a file named `index.ts` in the project folder and add the following code:

typescript
function greet(name: string) {
  return `Hello, ${name}!`;
}

console.log(greet("World"));

To compile TypeScript to JavaScript, run the command `npx tsc` in the terminal. This generates an `index.js` file which you can run with `node index.js` to see the output.

A common error beginners face is the "Cannot find module" or "file not found" error. This usually means the TypeScript compiler or Node.js cannot find your file or module. Make sure your terminal is inside the project directory, your file names are correct, and your tsconfig.json paths are set properly.

You are now ready to write and compile TypeScript code efficiently in Visual Studio Code. The editor also provides useful features like IntelliSense (code completion) and inline error highlighting to assist your coding journey.