.ts files, and manage your compiler settings.
First and foremost, let's talk about how you can set up TypeScript.
TypeScript can be either installed globally via npm or locally in your project. We'll first cover the global installation.
Npm allows us to install packages globally using the
-g flag. Once installed globally, you can access the package from any command line window on your machine. For TypeScript:
- To install globally, run:
npm install -g typescript
- Confirm the installation by running:
After you've set up TypeScript, create a new TypeScript file in Visual Studio Code and input a line to log out to the console. Next, compile this TypeScript file by opening a terminal and running
You can add more code to your TypeScript file and compile again using the
node index.js in the terminal.
While the basic setup is good for starters, you might want to tweak some compilation settings down the road.
Here's how you can get started with custom configurations:
- Add a
tsconfig.jsonfile in the root directory of your project.
tscwithout any arguments. TypeScript will recognize the
tsconfigfile and use the configurations specified there during compilation.
- Add compiler options like
Visual Studio Code provides fantastic support for TypeScript configurations:
- You can use
Ctrl + Space(or
Cmd + Spaceon Mac) to access IntelliSense, which shows you all the possible options for your
- Hovering over the configuration fields provides tooltips explaining their usage.
To avoid repeatedly running the
tsc command after every change, use
tsc --watch or
Ctrl + Shift + B in VSCode to compile TypeScript files automatically upon changes.
If your project uses a specific TypeScript version, you'd want VSCode to utilize that.
One of the highlights of TypeScript support in VSCode is the ability to debug TypeScript files directly.
Here's a step-by-step guide:
- Enable source maps in your
- When you compile with source maps enabled, a
- Configure the debugger in VSCode. Select
Run and Debugin the menu and choose "Create a launch.json file". Here, specify the pre-launch task, which should be the TypeScript compile command (
- Add breakpoints to your TypeScript file and start the debugger using the
Check out this video on our YouTube channel showing TypeScript in VSCode in action.