Setting Up TypeScript
Before you can start writing TypeScript code, you need to set up your development environment. Thankfully, setting up TypeScript is quick and easy. In this lesson, you'll learn how to install TypeScript, compile your code, and even add it to an existing JavaScript project.
Installing TypeScript and Setting Up Your Project
To use TypeScript, you first need to install it. You can do this globally on your system using npm (Node Package Manager). Just open your terminal and run:
npm install -g typescript
To create a new TypeScript project, make a folder and run this inside it:
tsc --init
This command creates a tsconfig.json
file, which tells TypeScript how to compile your code. It’s where you can set options like the output folder, which JavaScript version to use, and whether to allow JavaScript files.
Now, create a file named index.ts
— the .ts
extension means it’s a TypeScript file.
Using tsc to Compile TypeScript
TypeScript code can’t run directly in the browser or Node.js. It needs to be compiled (or converted) into regular JavaScript using the TypeScript compiler, which is called tsc
.
To compile your .ts
file into a .js
file, run:
tsc
This command looks at your tsconfig.json
and compiles all .ts
files in the project. You’ll see a new .js
file created—this is the version that runs in browsers or Node.js.
You can also compile a single file like this:
tsc index.ts
Integrating TypeScript with Existing JavaScript Projects
If you already have a JavaScript project, you don’t need to start over to use TypeScript. You can slowly add .ts
or .tsx
(for React) files one by one.
Start by installing TypeScript locally in your project:
npm install --save-dev typescript
Then run tsc --init
to generate the config file. After that, you can change any .js
file to .ts
and begin adding type annotations. TypeScript will work alongside your existing code without breaking anything.
This makes TypeScript very flexible—you can use it as little or as much as you like, depending on the needs of your project.