---
# System prepended metadata

title: Type Script intro
tags: [42-transcendence]

---

# Study Resources

-  TypeScript in 100 Seconds
https://www.youtube.com/watch?v=zQnBQ4tB3ZA&t=47s

-  A beginners guide to Typescript | Why use it? 
https://www.youtube.com/watch?v=ZY1Om-AOpBY

-  TypeScript - The Basics 
https://www.youtube.com/watch?v=ahCwqrYpIuM

- TypeScript Documentation
https://www.typescriptlang.org/docs/

- TypeScript Introduction 
https://www.w3schools.com/typescript/typescript_intro.php
- TypeScript | Cheat Sheet
https://www.typescriptlang.org/cheatsheets/

- perplexity suggests 
https://www.perplexity.ai/search/i-m-new-to-type-script-give-me-IgKiGo3QSC2r6BB1wLCC6w?0=d&login-new=false&login-source=sourcesViewMore



---


## 🔷 What's TypeScript?

### English:

TypeScript is a **superset of JavaScript** developed by Microsoft. It adds **static typing** and **additional features** to JavaScript, enabling developers to catch errors early and write more robust, scalable code. TypeScript code is compiled (or transpiled) into standard JavaScript before execution.

### 中文（繁體）：

TypeScript 是由微軟開發的 **JavaScript 超集**。它在 JavaScript 的基礎上增加了 **靜態型別** 和其他強大功能，讓開發者能在編譯時捕捉錯誤，撰寫更健壯且可擴展的程式碼。TypeScript 程式碼需先轉譯為標準的 JavaScript 才能執行。

---
# What's TypeScript?

## 🔷 What are TypeScript’s features?

### English:

* **Static Typing**: Variables, function parameters, and return types can be explicitly typed.
* **Type Inference**: TypeScript can infer types even when not explicitly defined.
* **Interfaces and Types**: For defining structured contracts in code.
* **Advanced IDE Support**: Better autocompletion, navigation, and refactoring in editors like VS Code.
* **Compile-Time Checking**: Catches errors before runtime.
* **Modern JavaScript Features**: Supports ES6+ syntax and features.
* **Decorators and Metadata**: Experimental support for advanced OOP features.

### 中文（繁體）：

* **靜態型別**：變數、函式參數與回傳值可以明確定義型別。
* **型別推斷**：即使未明確宣告型別，TypeScript 也可自動判斷。
* **介面與型別別名**：用來定義結構化的型別合約。
* **強大的編輯器支援**：在 VS Code 等 IDE 中提供更佳的自動完成、導覽與重構功能。
* **編譯時檢查**：可在執行前偵測錯誤。
* **支援現代 JavaScript 語法**：支援 ES6 以上的語法與功能。
* **裝飾器與中繼資料**：實驗性支援進階的物件導向功能。

---

## 🔷 Why and when to use TypeScript?

### English:

**Why:**

* Reduces runtime bugs.
* Improves code quality and maintainability.
* Enhances developer productivity and collaboration.
* Ideal for large-scale applications.

**When:**

* When working on **complex or long-term projects**.
* In **teams**, to ensure consistent code.
* When integrating with **modern frameworks** (e.g., Angular, React, Vue).
* When code **reliability and readability** are priorities.

### 中文（繁體）：

**為什麼使用：**

* 減少執行階段錯誤。
* 提高程式碼品質與可維護性。
* 增進開發效率與團隊協作。
* 適合大型應用程式開發。

**什麼時候使用：**

* 當你開發**複雜或長期維護的專案**。
* **團隊開發**時，需要統一的程式風格與型別。
* 搭配 **現代框架**（如 Angular、React、Vue）使用。
* 需要提高程式碼的 **可讀性與可靠性** 時。

---

## 🔷 What's the difference between TypeScript & JavaScript?

### English:

| Aspect          | JavaScript                      | TypeScript                              |
| --------------- | ------------------------------- | --------------------------------------- |
| Typing          | Dynamically typed               | Statically typed (with optional typing) |
| Error Detection | Runtime                         | Compile-time                            |
| Compilation     | Interpreted directly by browser | Needs to be compiled to JavaScript      |
| Tooling Support | Basic                           | Advanced (IDE, type checks, refactors)  |
| Learning Curve  | Lower                           | Higher (due to type system)             |
| Use Case        | Simple to intermediate apps     | Complex, large-scale applications       |

### 中文（繁體）：

| 比較項目 | JavaScript | TypeScript        |
| ---- | ---------- | ----------------- |
| 型別系統 | 動態型別       | 靜態型別（可選擇性使用）      |
| 錯誤偵測 | 執行階段發現     | 編譯階段檢查            |
| 編譯需求 | 瀏覽器可直接執行   | 必須先轉譯為 JavaScript |
| 工具支援 | 基本         | 進階（IDE、自動完成、重構等）  |
| 學習曲線 | 低          | 較高（因型別系統）         |
| 適用場景 | 簡單或中型應用    | 複雜或大型應用程式         |

---

## ✅ Summary Table

| Topic           | JavaScript               | TypeScript                                 |
| --------------- | ------------------------ | ------------------------------------------ |
| Language Type   | Scripting language       | Superset of JavaScript                     |
| Typing          | Dynamic                  | Static (with type annotations)             |
| Compilation     | Not required             | Required (transpiles to JS)                |
| Error Detection | At runtime               | At compile time                            |
| Tooling         | Basic                    | Advanced IDE support                       |
| Use Case        | Small to medium projects | Large, scalable, maintainable applications |
| Learning Curve  | Easy to learn            | Requires additional type system knowledge  |


---


## 🔷 What is a **"type"**?

### 📘 English:

In programming, a **type** defines the **kind of value** a variable can hold. It tells the computer what kind of data to expect—like a **number**, **string**, **boolean**, **array**, or **object**.

Examples of common types:

* `number`: Numeric values like `42`, `3.14`
* `string`: Text like `"hello"`
* `boolean`: `true` or `false`
* `array`: A list like `[1, 2, 3]`
* `object`: A structure like `{ name: "John", age: 30 }`

Types help ensure that the program behaves correctly and predictably.

---

### 📗 中文（繁體）：

在程式設計中，「**型別（type）**」定義了一個變數可以儲存的**資料種類**。它告訴電腦預期收到什麼樣的資料，例如：**數字**、**字串**、**布林值**、**陣列**或**物件**。

常見的型別包括：

* `number`：數值，例如 `42`、`3.14`
* `string`：文字，例如 `"hello"`
* `boolean`：布林值，`true` 或 `false`
* `array`：陣列，例如 `[1, 2, 3]`
* `object`：物件，例如 `{ name: "John", age: 30 }`

型別有助於確保程式行為正確、穩定。

---

## 🔷 What are **type annotations**?

### 📘 English:

A **type annotation** is the **explicit declaration** of a variable's type in your code. It tells the compiler what type the variable is **supposed** to be.

In TypeScript:

```ts
let age: number = 25;
let name: string = "Alice";
let isOnline: boolean = true;
```

Here, `: number`, `: string`, and `: boolean` are **type annotations**. They help the compiler catch type-related errors before running the code.

---

### 📗 中文（繁體）：

**型別註記（type annotation）**是指你在程式中**明確標示變數型別**的做法。這讓編譯器知道這個變數**應該是什麼型別**。

在 TypeScript 中：

```ts
let age: number = 25;
let name: string = "Alice";
let isOnline: boolean = true;
```

其中 `: number`、`: string`、`: boolean` 就是 **型別註記**。這樣可以幫助編譯器在執行前偵測型別錯誤，提升程式的安全性與可維護性。

---

## ✅ Summary

| Concept             | English Definition                                                               | 中文定義                        |
| ------------------- | -------------------------------------------------------------------------------- | --------------------------- |
| **Type**            | The category of data a variable holds (e.g., number, string, boolean)            | 變數所儲存的資料類型（如：數字、字串、布林值）     |
| **Type Annotation** | Explicitly stating the type of a variable in code (e.g., `: number`, `: string`) | 在程式中明確標示變數型別（例如 `: number`） |


---


## 🔷 When to Use TypeScript vs JavaScript

### 📘 English

### ✅ Use **TypeScript** when:

* You're building a **large-scale application** with many files and modules.
* You're working with a **team**, and want **strong type safety** and **developer tooling**.
* You need **predictable behavior**, and want to **catch errors before runtime**.
* You're using modern frameworks like **Angular**, **React**, or **Vue** in large apps.
* You want **maintainable**, **self-documenting** code that scales over time.

### ✅ Use **JavaScript** when:

* You’re building a **small script** or **simple application**.
* You want to **prototype quickly** without setting up a build step.
* You're working on **front-end logic** that runs directly in the browser.
* You're learning the **basics of programming or the web**.
* You're writing **non-critical, one-time code** (e.g., quick automation).

---

### 📗 中文（繁體）

### ✅ 什麼時候使用 **TypeScript**：

* 當你開發一個**大型應用程式**，包含很多檔案與模組時。
* 當你在一個**團隊合作**的專案中，需要**嚴謹的型別檢查**與**強大開發工具支援**。
* 當你需要**可預測的行為**，並希望在**執行前發現錯誤**。
* 當你使用像 **Angular**、**React** 或 **Vue** 等現代框架建構大型應用。
* 當你希望程式碼具備良好的**可維護性**與**可讀性**。

### ✅ 什麼時候使用 **JavaScript**：

* 當你只需要開發一個**小工具或簡單應用**。
* 當你想**快速原型開發**，不想設定轉譯環境。
* 當你編寫的是直接**在瀏覽器中執行的前端程式碼**。
* 當你還在學習**程式設計或前端技術的基礎**。
* 當你撰寫的是**一次性、非關鍵性的小程式**（例如自動化腳本）。

---

## 🧪 Code Example: JavaScript vs TypeScript

### 🔹 JavaScript (No type checking)

```javascript
function greet(user) {
  return "Hello, " + user.toUpperCase(); // Runtime error if user is not a string
}

console.log(greet(123)); // Error at runtime
```

### 🔹 TypeScript (With type annotations and compile-time error)

```typescript
function greet(user: string): string {
  return "Hello, " + user.toUpperCase();
}

console.log(greet(123)); // ❌ Compile-time error: Argument of type 'number' is not assignable to parameter of type 'string'
```

> TypeScript catches the problem **before execution** — making your code safer.

---

## ✅ Summary Table

| Criteria             | Use **JavaScript** | Use **TypeScript**                        |
| -------------------- | ------------------ | ----------------------------------------- |
| Project Size         | Small / simple     | Medium to large / complex                 |
| Development Speed    | Fast prototyping   | Structured, scalable development          |
| Error Detection      | Runtime            | Compile-time                              |
| Code Maintainability | Low to medium      | High (strong typing and tooling)          |
| Tooling Support      | Basic              | Advanced (autocompletion, refactor, lint) |
| Team Collaboration   | Less safe          | Safer with enforced types                 |
| Learning Curve       | Easy               | Requires understanding of types           |
| Setup Required       | None               | Requires build tools (e.g., tsconfig)     |

---
---

# 🔑 Essential TypeScript Syntax & Features for Beginners

### 📘 English + 📗 中文（繁體）

---

### 1. **Basic Type Annotations**

Tell TypeScript what type a variable should be.

```ts
let age: number = 25;
let name: string = "Alice";
let isActive: boolean = true;
```

📗 用來指定變數的資料型別，例如數字、字串、布林值。

---

### 2. **Function Type Annotations**

Specify parameter and return types for functions.

```ts
function greet(name: string): string {
  return "Hello, " + name;
}
```

📗 在函式中標註參數與回傳值的型別，有助於防止錯誤。

---

### 3. **Interfaces**

Define a structure (contract) for an object.

```ts
interface User {
  id: number;
  name: string;
}

const user: User = { id: 1, name: "John" };
```

📗 `interface` 定義物件的結構，確保物件具有正確的屬性與型別。

---

### 4. **Optional & Default Parameters**

Mark parameters as optional or assign default values.

```ts
function log(message: string, userId?: number) {
  console.log(message, userId);
}

function multiply(a: number, b: number = 1): number {
  return a * b;
}
```

📗 使用 `?` 表示參數可選，用 `=` 設定預設值。

---

### 5. **Type Aliases (`type`)**

Create reusable custom types.

```ts
type ID = number | string;
let userId: ID = 101;
```

📗 使用 `type` 建立自訂型別，尤其適用於聯合型別（多種可能型別）。

---

### 6. **Union & Literal Types**

A variable can accept **more than one** type or **specific values only**.

```ts
let status: "success" | "error" = "success";
let id: number | string = 123;
```

📗 聯合型別允許變數擁有多種型別。字面型別限制變數只能取某些值。

---

### 7. **Arrays and Tuples**

Define typed arrays and fixed-structure tuples.

```ts
let scores: number[] = [100, 98, 95];
let person: [string, number] = ["Alice", 25];
```

📗 陣列使用 `type[]` 表示，Tuple 則是固定型別與順序的陣列。

---

### 8. **Enums**

Create named constants for readability.

```ts
enum Direction {
  Up,
  Down,
  Left,
  Right
}

let move: Direction = Direction.Up;
```

📗 `enum` 是列舉型別，用來定義一組可讀性高的常數。

---

### 9. **Type Inference**

TypeScript can guess the type if a value is assigned.

```ts
let message = "Hello"; // inferred as string
```

📗 不需要每次都標註型別，TypeScript 會根據賦值自動推斷。

---

### 10. **Any & Unknown Types**

Use when the type is uncertain — but be cautious.

```ts
let data: any = 123;
let value: unknown = "text";
```

📗 `any` 允許任何型別（沒保障），`unknown` 較安全，但需先檢查型別才能使用。

---

### 11. **Type Assertions**

Tell TypeScript to treat a value as a specific type.

```ts
let someValue: any = "hello";
let strLength: number = (someValue as string).length;
```

📗 類似型別轉換，用於你確信變數的實際型別時。

---

### 12. **Generics**

Write reusable, type-safe code.

```ts
function identity<T>(value: T): T {
  return value;
}

let output = identity<string>("hello");
```

📗 `Generics` 泛型讓函式或類別支援不同型別的資料，並保持型別安全。

---

## ✅ Summary Table

| Feature            | Syntax Example                             | 中文解說       |      |
| ------------------ | ------------------------------------------ | ---------- | ---- |
| Variable Type      | `let name: string = "Alice"`               | 變數型別       |      |
| Function Type      | `function greet(name: string): string`     | 函式型別       |      |
| Interface          | `interface User { name: string }`          | 定義物件結構     |      |
| Optional Parameter | `function log(msg: string, id?: number)`   | 可選參數       |      |
| Type Alias         | \`type ID = number                         | string\`   | 自訂型別 |
| Union Type         | \`let x: number                            | string\`   | 聯合型別 |
| Array / Tuple      | `let scores: number[]`, `[string, number]` | 陣列與 Tuple  |      |
| Enum               | `enum Color { Red, Blue }`                 | 列舉型別       |      |
| Type Inference     | `let x = true`                             | 型別推斷       |      |
| Any / Unknown      | `let x: any`, `let y: unknown`             | 任意型別／未知型別  |      |
| Type Assertion     | `(value as string).length`                 | 型別斷言（類型轉換） |      |
| Generics           | `function identity<T>(value: T): T`        | 泛型         |      |

