In this tutorial, you’ll learn how to set up a new TypeScript project from scratch. We'll cover installing the necessary tools, configuring TypeScript, and writing your first TypeScript file.
TypeScript is a powerful, statically typed superset of JavaScript that enhances development by providing features like type safety, autocompletion, and better error detection. Setting up a new TypeScript project allows you to harness these benefits while maintaining compatibility with JavaScript
Prerequisites
Before getting started, make sure you have the following:
- Basic knowledge of TypeScript and JavaScript.
How To Set Up a New TypeScript Project
Step 1: Install Node.js and npm
Following commands copied from NodeJS official website. This the package manager.
# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
# download and install Node.js (you may need to restart the terminal)
nvm install 20
# verifies the right Node.js version is in the environment
node -v # should print `v20.17.0`
# verifies the right npm version is in the environment
npm -v # should print `10.8.2`
Step 2: Set Up a New Project Directory
Create a new directory for your project and navigate into it:
mkdir my-typescript-project
cd my-typescript-project
Step 3: Initialize npm
To initialize your project and create a package.json file, run:
npm init -y
Output:
{
"name": "my-typescript-project",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
This command generates a default package.json file, which will manage your project’s dependencies and scripts.
Step 4: Install TypeScript
Now, install TypeScript as a development dependency:
npm install typescript --save-dev
Installing TypeScript as a dev dependency ensures it's only required for development purposes, not in production.
Step 5: Initialize TypeScript Configuration
To configure TypeScript, create a tsconfig.json
file. This file tells the TypeScript compiler how to process your code.
Run the following command to generate a basic tsconfig.json:
npx tsc --init
This will create a tsconfig.json file with default configurations. You can customize it to fit your project’s needs. Here’s a typical configuration:
nano tsconfig.json
Similar output. We have removed all comments here:
{
"compilerOptions": {
"target": "es6", // Specifies ECMAScript target version
"module": "commonjs", // Specifies module code generation
"strict": true, // Enable strict type-checking options
"esModuleInterop": true, // Emit additional helper for importing CommonJS modules
"skipLibCheck": true, // Skip type checking of declaration files
"outDir": "./dist", // Redirect output structure to the directory
"rootDir": "./src" // Specify the root directory of input files
},
"include": ["src/**/*"] // Include files in the src folder
}
This configuration:
- Targets ECMAScript 6.
- Uses CommonJS as the module system.
- Enforces strict type checking.
- Outputs compiled files to the dist folder.
Step 6: Create the Source Directory
In most TypeScript projects, you'll organize your code under a src directory. Create this directory:
mkdir src
Inside src, create a simple TypeScript file, index.ts:
nano src/index.ts
Write your first TypeScript file. Add the following code:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet('TypeScript'));
This code defines a simple greet function that takes a string name as an argument and returns a greeting. The TypeScript compiler will check the types, ensuring the argument is always a string.
Step 7: Compile TypeScript
To compile your TypeScript code into JavaScript, run:
npx tsc
The compiled JavaScript code will be generated in the dist directory as specified in the tsconfig.json. You’ll now have src/index.js
containing the compiled version of your TypeScript code.
Step 8: Run the Compiled JavaScript
You can now run the compiled JavaScript using Node.js:
node src/index.js
You should see the output:
Hello, TypeScript!
Step 9: Automate the Build Process (Optional)
You can add a script to your package.json file to make it easier to compile TypeScript without manually running the npx tsc command each time.
Open package.json and add the following script:
"scripts": {
"build": "tsc"
}
Now, you can compile your TypeScript code by simply running:
npm run build
Step 10: Watch Mode for Automatic Compilation (Optional)
To automatically recompile your TypeScript files when you make changes, you can use TypeScript’s watch mode. Add a new script in package.json for watch mode:
"scripts": {
"build": "tsc",
"watch": "tsc --watch"
}
Now, you can run:
npm run watch
This will automatically recompile TypeScript files whenever you make changes.
Conclusion
You’ve now successfully set up a new TypeScript project, written a TypeScript file, and compiled it to JavaScript. From here, you can expand your project by adding more TypeScript files, modules, and functionality. With TypeScript, you can enjoy more robust code through better tooling and type safety, ultimately making your development process more efficient.
Happy coding!
Checkout our dedicated servers and KVM VPS