TypeScript Tutorial

TypeScript is a statically typed superset of JavaScript that adds optional static typing to the language.

1. Installing TypeScript

First, you need to install TypeScript globally using npm (Node Package Manager). Make sure you have Node.js installed.

bash
npm install -g typescript

2. Creating Your First TypeScript File

Create a new file named hello.ts (the ".ts" extension indicates a TypeScript file):

typescript
function greet(name: string) { return `Hello, ${name}!`; } const message = greet('World'); console.log(message);

3. Compiling TypeScript to JavaScript

Compile the TypeScript file to JavaScript using the TypeScript compiler (tsc):

bash
tsc hello.ts

This will generate a hello.js file.

4. Running the JavaScript Code

You can now run the generated JavaScript code:

bash
node hello.js

5. Understanding Basic TypeScript Syntax

  • Variables and Types:
typescript
let num: number = 10; let str: string = 'Hello'; let bool: boolean = true; let arr: number[] = [1, 2, 3]; let tuple: [string, number] = ['example', 123]; let anyType: any = 5; // Can be any type // Functions function add(a: number, b: number): number { return a + b; } // Objects let person: { name: string; age: number } = { name: 'John Doe', age: 30, };
  • Interfaces:
typescript
interface Person { name: string; age: number; } const user: Person = { name: 'Alice', age: 25, };
  • Classes:
typescript
class Car { private speed: number; constructor(speed: number) { this.speed = speed; } accelerate() { this.speed += 10; } } const myCar = new Car(50); myCar.accelerate();

6. TypeScript Compiler Configuration

Create a tsconfig.json file in your project directory to configure TypeScript settings:

json
{ "compilerOptions": { "outDir": "./dist", "target": "ES6", "module": "CommonJS", "strict": true, "esModuleInterop": true }, "include": ["**/*.ts"], "exclude": ["node_modules"] }

This configuration tells TypeScript to output the compiled JavaScript files to the "dist" directory.

7. Compiling and Running with ts-node

To directly run TypeScript files without compiling to JavaScript, you can use ts-node. Install it globally using npm:

bash
npm install -g ts-node

Now you can run your TypeScript files directly:

bash
ts-node hello.ts

This tutorial covers the basics of TypeScript. As you become more familiar with TypeScript, you can explore more advanced features and concepts such as generics, decorators, async/await, and more. Happy coding!

Comments