Setting up TypeScript on your local system involves a few steps. TypeScript is a superset of JavaScript that adds static typing to the language, and it compiles down to plain JavaScript.
TypeScript relies on Node.js and npm for package management. You can download and install Node.js.
Visit the official Node.js website: Node.js
Follow the installation instructions for your operating system. This will also install npm (Node Package Manager).
Open a terminal or command prompt and run the following commands to verify that Node.js and npm are installed:
node -v
npm -v
You should see version numbers for Node.js and npm.
Open a terminal or command prompt and run the following command to install TypeScript globally using npm:
npm install -g typescript
This installs the TypeScript compiler (tsc
) globally on your system.
Run the following command to check the TypeScript version:
tsc -v
You should see the installed TypeScript version.
Choose or create a directory for your TypeScript project. Open a terminal, navigate to this directory, and create a new folder for your project.
mkdir mytypescriptproject
cd mytypescriptproject
Run the following command to create a package.json file. Follow the prompts to provide information about your project.
npm init
Inside your project directory, create a new TypeScript file with a .ts
extension. For example, app.ts
. You can use any code editor of your choice, such as Visual Studio Code, Sublime Text, or Atom.
Write your TypeScript code in the .ts
file.
// app.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
const result = greet("TypeScript");
console.log(result);
You can create a tsconfig.json file to configure TypeScript compilation options. This file can include compiler options, file inclusion/exclusion settings, and more.
Run the following command to generate a basic tsconfig.json file:
npx tsc --init
This will create a default tsconfig.json file that you can customize.
Open the generated tsconfig.json file and customize it according to your project requirements.
Open a terminal or command prompt and navigate to the directory containing your TypeScript file. Run the following command to compile the TypeScript code into JavaScript:
tsc app.ts
This will generate a corresponding JavaScript files('app.js`) based on your TypeScript code.
Now you can run the generated JavaScript code using Node.js:
node app.js