> For the complete documentation index, see [llms.txt](https://testingvn.gitbook.io/playwright/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://testingvn.gitbook.io/playwright/setup/typescript-fundamental.md).

# Typescript fundamental

### 1. Hello World!

TypeScript is a superset of JavaScript that adds static types to the language. Let's start with a simple "Hello World" program.

**Example**:

```typescript
console.log("Hello, World!");
```

To run this:

1. Save it as `hello.ts`.
2. Compile it to JavaScript using the TypeScript compiler: `tsc hello.ts`.
3. Run the generated `hello.js` file with Node.js: `node hello.js`.

***

### 2. Variables, Constants, and Data Types

TypeScript supports variables and constants with explicit type annotations. Common data types include `number`, `string`, `boolean`, `any`, and more.

#### Variables

Use `let` or `const` for variables. TypeScript infers types when not explicitly declared.

**Example**:

```typescript
let name: string = "Alice";
let age: number = 25;
let isStudent: boolean = true;
let dynamic: any = "Can be anything";
```

#### Constants

Use `const` for values that won't change.

**Example**:

```typescript
const PI: number = 3.14;
```

#### Other Data Types

* `null` and `undefined`
* `object`, `array`, `tuple`, `enum`, etc. (covered later).

***

### 3. Concatenation and Interpolation

You can combine strings using concatenation (`+`) or template literals for interpolation.

**Concatenation**:

```typescript
let firstName: string = "John";
let lastName: string = "Doe";
let fullName: string = firstName + " " + lastName;
console.log(fullName); // Output: John Doe
```

**Interpolation** (using template literals):

```typescript
let greeting: string = `Hello, ${firstName} ${lastName}!`;
console.log(greeting); // Output: Hello, John Doe!
```

***

### 4. Objects and Arrays

#### Objects

Objects in TypeScript can have defined types for their properties.

**Example**:

```typescript
let person: { name: string; age: number } = {
    name: "Alice",
    age: 30
};
console.log(person.name); // Output: Alice
```

#### Arrays

Arrays hold multiple values of the same type.

**Example**:

```typescript
let numbers: number[] = [1, 2, 3, 4];
let names: Array<string> = ["Alice", "Bob", "Charlie"];
console.log(numbers[0]); // Output: 1
console.log(names.length); // Output: 3
```

#### Tuples

Fixed-length arrays with specific types.

**Example**:

```typescript
let tuple: [string, number] = ["Alice", 25];
console.log(tuple[0]); // Output: Alice
```

***

### 5. Relational and Equality Operators

elational operators compare values, and equality operators check for equality.

#### Relational Operators

* <, >, <=, >=

**Example**:

```typescript
let a: number = 10;
let b: number = 20;
console.log(a < b); // Output: true
console.log(a >= b); // Output: false
```

#### Equality Operators

* \== (loose equality, type coercion)
* \=== (strict equality, no type coercion)
* !=, !==

**Example**:

```typescript
let x: number = 5;
let y: string = "5";
console.log(x == y); // Output: true
console.log(x === y); // Output: false

```

### 6. Logical Operators

Logical operators combine conditions: && (AND), || (OR), ! (NOT).

**Example**:

```typescript
let isAdult: boolean = true;
let hasLicense: boolean = false;

console.log(isAdult && hasLicense); // Output: false
console.log(isAdult || hasLicense); // Output: true
console.log(!isAdult); // Output: false
```

***

### 7. Conditional Statements

Conditional statements control the flow of execution based on conditions.

#### If-Else

```typescript
let age: number = 18;
if (age >= 18) {
    console.log("Adult");
} else {
    console.log("Minor");
}
// Output: Adult
```

#### Switch

```typescript
let day: number = 2;
switch (day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    default:
        console.log("Other day");
}
// Output: Tuesday
```

***

### 8. Loops

Loops allow repetitive execution of code.

#### For Loop

```typescript
for (let i: number = 0; i < 5; i++) {
    console.log(i);
}
// Output: 0, 1, 2, 3, 4
```

#### While Loop

```typescript
let count: number = 0;
while (count < 3) {
    console.log(count);
    count++;
}
// Output: 0, 1, 2
```

#### For...of Loop (for arrays)

```typescript
let fruits: string[] = ["Apple", "Banana", "Orange"];
for (let fruit of fruits) {
    console.log(fruit);
}
// Output: Apple, Banana, Orange
```

### 9. Functions

Functions in TypeScript can have typed parameters and return types.

**Example**:

```typescript
function add(a: number, b: number): number {
    return a + b;
}
console.log(add(5, 3)); // Output: 8
```

#### Optional Parameters

```typescript
function greet(name: string, greeting?: string): string {
    return `${greeting || "Hello"}, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob", "Hi")); // Output: Hi, Bob!
```

#### Arrow Functions

```typescript
const multiply = (x: number, y: number): number => x * y;
console.log(multiply(4, 5)); // Output: 20
```

***

### 10. Classes and Methods

Classes define blueprints for objects with properties and methods.

**Example**:

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

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

    introduce(): string {
        return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
    }
}

let person: Person = new Person("Alice", 25);
console.log(person.introduce()); // Output: Hi, I'm Alice and I'm 25 years old.
```

#### Inheritance

```typescript
class Student extends Person {
    grade: number;

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

    study(): string {
        return `${this.name} is studying.`;
    }
}

let student: Student = new Student("Bob", 20, 10);
console.log(student.introduce()); // Output: Hi, I'm Bob and I'm 20 years old.
console.log(student.study()); // Output: Bob is studying.
```

***

### 11. Practice Exercises

Try these exercises to test your understanding of TypeScript fundamentals.

1. **Hello World Modification**\
   Create a program that prints "Welcome to TypeScript!" to the console.
2. **Variable Swap**\
   Declare two variables a and b with numbers, swap their values, and print the result.
3. **String Interpolation**\
   Create a function that takes a name and age and returns a string like "Hello, \[name]! You are \[age] years old."
4. **Array Sum**\
   Write a function that takes an array of numbers and returns their sum.
5. **Object Creation**\
   Define an object type for a Car with properties brand (string) and year (number). Create an instance and print its properties.
6. **Equality Check**\
   Write a function that checks if two numbers are equal using both == and === and explains the difference in output.
7. **Logical Operator Task**\
   Create a function that takes age and hasLicense and returns true only if the person is over 18 and has a license.
8. **Grade Calculator**\
   Write a program that takes a score (0-100) and prints a letter grade (A, B, C, D, F) using if-else or switch.
9. **Loop Exercise**\
   Write a loop that prints all even numbers from 1 to 20.
10. **Class Creation**\
    Create a Rectangle class with width and height properties and a method getArea() that returns the area. Test it with an instance.
