# TypeScript

### **Introduction**

TypeScript (TS) is a **strongly typed, object-oriented** programming language that extends JavaScript by adding **static types**. Developed by **Microsoft**, TypeScript is designed for **scalability, maintainability, and developer productivity**. It compiles down to JavaScript and is widely used in frontend and backend development.

### **Why Use TypeScript?**

* **Static Typing** – Catches errors at compile time.
* **Better Code Maintainability** – Enforces coding standards and documentation.
* **Object-Oriented Features** – Supports interfaces, classes, and modules.
* **Works with JavaScript** – TypeScript is a superset of JavaScript.
* **Great for Large-Scale Projects** – Used by companies like Microsoft, Google, and Airbnb.
* **IDE Support** – Enhanced autocompletion, refactoring, and type checking in VS Code.

## **Installing TypeScript**

### **1️⃣ Install TypeScript**

#### **Install Globally Using npm**

```bash
npm install -g typescript

```

### **2️⃣ Writing Your First TypeScript Program**

Create a new file **`hello.ts`** and add:

```typescript
function greet(name: string): string {
    return `Hello, ${name}!`;
}

console.log(greet("TypeScript 🚀"));

```

**Compile & Run the Code**

```bash
tsc hello.ts  # Compiles to hello.js
node hello.js # Runs the JavaScript output

```

**Output:** `"Hello, TypeScript 🚀"`

## **TypeScript Basics**

### **1️⃣ Variables & Data Types**

```typescript
let firstName: string = "Alice";
let age: number = 25;
let isDeveloper: boolean = true;

const skills: string[] = ["TypeScript", "React", "Node.js"];

console.log(firstName, age, isDeveloper, skills);

```

### 2️⃣ Functions in TypeScript

```typescript
function add(a: number, b: number): number {
    return a + b;
}

console.log(add(5, 3)); // Output: 8

```

**Optional & Default Parameters:**

```typescript
function greet(name: string, lang: string = "English"): string {
    return `Hello, ${name}! Language: ${lang}`;
}

console.log(greet("Alice"));
console.log(greet("Bob", "French"));

```

### **3️⃣ Interfaces in TypeScript**

**Define an Interface**

```typescript
interface User {
    name: string;
    age: number;
    isAdmin?: boolean;  // Optional Property
}

const user: User = { name: "Alice", age: 25 };
console.log(user);

```

### 4️⃣ Classes & Object-Oriented Programming (OOP)

```typescript
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    greet(): string {
        return `Hello, my name is ${this.name}.`;
    }
}

const person1 = new Person("Alice", 30);
console.log(person1.greet());

```

## **TypeScript for Web Development**

### **1️⃣ Setting Up a TypeScript Project**

#### **Initialize a TypeScript Project**

```bash
tsc --init

```

This creates a **`tsconfig.json`** file to configure TypeScript.

### **2️⃣ Using TypeScript with React (Frontend)**

**Create a React App with TypeScript**

```bash
npx create-react-app my-app --template typescript

```

Using TypeScript in React

```jsx
interface ButtonProps {
    label: string;
}

const Button: React.FC<ButtonProps> = ({ label }) => {
    return <button>{label}</button>;
};

export default Button;

```

### **3️⃣ Using TypeScript with Node.js (Backend)**

**Install Required Packages**

```bash
npm install express cors body-parser
npm install --save-dev @types/node @types/express

```

Create a TypeScript Express Server

```typescript
import express, { Request, Response } from "express";

const app = express();
const PORT = 3000;

app.get("/", (req: Request, res: Response) => {
    res.send("Hello from TypeScript Express Server!");
});

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

```

Run

```bash
tsc && node dist/index.js

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.anandisheladiya.com/skills-and-experience/backend/typescript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
