Programming Language
TypeScript
Introduction
TypeScript First Code

TypeScript First Code

Welcome to your first TypeScript code! In this guide, we will walk you through writing and running your first TypeScript program. TypeScript is a powerful, statically typed superset of JavaScript that helps you write more robust and maintainable code.

Prerequisites

Before you start, make sure you have the following installed:

Step 1: Set Up Your Project

First, create a new directory for your project and navigate into it:

mkdir my-first-typescript-project
cd my-first-typescript-project

Initialize a new Node.js project:

npm init -y

This will create a package.json file in your project directory.

Step 2: Install TypeScript

Next, install TypeScript as a development dependency:

npm install typescript --save-dev

You can also install TypeScript globally if you prefer:

npm install -g typescript

Step 3: Create a tsconfig.json File

The tsconfig.json file is used to configure the TypeScript compiler. Create this file in the root of your project:

npx tsc --init

This command generates a tsconfig.json file with default settings. You can customize this file according to your project's requirements. Here is an example configuration:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist"
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

Step 4: Write Your First TypeScript Code

Create a src directory and add a TypeScript file:

mkdir src
touch src/index.ts

Open src/index.ts and add the following code:

const greeting: string = "Hello, TypeScript!";
console.log(greeting);

Step 5: Compile TypeScript Code

To compile your TypeScript code to JavaScript, run the TypeScript compiler:

npx tsc

This will compile the TypeScript files in the src directory and output the JavaScript files to the dist directory (as specified in tsconfig.json).

Step 6: Run the Compiled JavaScript

You can now run the compiled JavaScript code using Node.js:

node dist/index.js

You should see the output Hello, TypeScript! in the console.

Conclusion

Congratulations! You have successfully written and run your first TypeScript code. You can now start building your TypeScript project with confidence. For more advanced configurations and features, refer to the TypeScript documentation (opens in a new tab).