1. Install Node.js and npm
To run TypeScript, you must have Node.js and its package manager npm installed. Download: Go to https://nodejs.org and download the LTS version.Verify Installation:
Open your terminal and run:
node -v
npm -v
You should see the version numbers of Node.js and npm if everything is installed correctly.
2. Create a New Project Folder
Create a folder where you'll set up your TypeScript project:
mkdir my-ts-project
cd my-ts-project
3. Initialize Your Project with npm
Run the following command to generate a package.json file:
npm init -y
The -y flag automatically accepts all default values.
4. Install TypeScript
Install TypeScript as a development dependency:
npm install typescript --save-dev
5. Create TypeScript Configuration File
Generate the tsconfig.json file, which stores the configuration settings for the TypeScript compiler:
npx tsc --init
This will create a default config file. You can later customize it based on your project's needs.
6. Create Your First TypeScript File
Create a folder named src and add a file named index.ts inside it:
mkdir src
touch src/index.ts
Now, add the following code inside src/index.ts:
function greet(name: string): string {
Hello, ${name}!
return;
}
console.log(greet("Joyonto"));
7. Compile TypeScript into JavaScript
To compile your TypeScript code, run:
npx tsc
This will compile your .ts file into a .js file. By default, it will create the compiled file in the same folder unless you specify an outDir in tsconfig.json.
Example:
src/index.ts → src/index.js
8. Run the Compiled JavaScript File
Now run your JavaScript file with Node.js:
node src/index.js
You should see the output:
Hello, Joyonto!
9. (Optional) Add Scripts to package.json
To simplify your workflow, you can add scripts to your package.json like this:
"scripts": {
"build": "tsc",
"start": "node src/index.js"
}
Now you can run:
npm run build # Compiles the TypeScript code
npm start # Runs the compiled JavaScript
thanks vai