A Beginner Guide to Configuring a Project with TypeScript
What is TypeScript?
Have you been studying TypeScript?
Not sure how to implement it into an actual project?
This tutorial is for you!
Create your project folder, then navigate inside.
Create a package.json file.
npm init --yes
Install Node Packages
Add TypeScript as a dev dependency.
npm install --save-dev typescript
Install tsc-watch. This program watches for changes to your TypeScript files and reloads upon on detection.
npm install --save-dev tsc-watch
Both packages will be saved into a
Create a tsconfig.json File
This is where the TypeScript compiler options will be defined. To create a
tsconfig.json, run the following:
npx tsc --init --rootDir src --outDir build \
--esModuleInterop --resolveJsonModule --lib es6 \
--module commonjs --allowJs true --noImplicitAny true
The command is courtesy of Khalil Stemmler’s TypeScript tutorial, which also provides an excellent breakdown of all the flags:
rootDir: This is where TypeScript looks for our code. We've configured it to look in the
src/folder. That's where we'll write our TypeScript.
outDir: Where TypeScript puts our compiled code. We want it to go to a
commonjsas our module system (for Node apps, you should be), then we need this to be set to
resolveJsonModule: If we use JSON in this project, this option allows TypeScript to use it.
lib: This option adds ambient types to our project, allowing us to rely on features from different Ecmascript versions, testing libraries, and even the browser DOM api. We'd like to utilize some
es6language features. This all gets compiled down to
commonjsis the standard Node module system in 2019. Let's use that.
noImplicitAny: In TypeScript files, don't allow a type to be unexplicitly specified. Every type needs to either have a specific type or be explicitly declared
any. No implicit
For the sake of this tutorial, we’ll need to add
"lib", like so:
“lib”: [“es6”, “DOM”],
Create the src Folder and First TypeScript File
Now, let’s create the
./src folder that will house the main TypeScript file.
index.ts file inside the
Then, add the following code to the
Let’s write some quick code to make sure our program is working. Navigate to the root directory and create an
index.html file. Copy and paste the following code:
Compiling Your Code
To compile your code simple run:
Open index.html in the browser. Wait 3 seconds. When you see “I’m using TypeScript” you’ll know your program is working!
You did it!
The compiled code can be found inside
Any errors will be displayed in the terminal like so: