1. Explore basic types of typescript
Tags: javascript, typescript, webdev, programming
Published: 2023-11-18 07:35:10


**
## **1-2 install typescript and node version manager in **ubuntu** **
_
To install TypeScript and Node Version Manager (nvm) on your Ubuntu Linux system, you can follow these steps:

**1. Install Node Version Manager (nvm):**

First, open your terminal and run the following commands to install nvm:

```bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
```

This command will download and execute the nvm installation script.

After the installation is complete, close and reopen your terminal, or run:

```bash
source ~/.bashrc
```

This will load nvm into your current shell session.

**. Install Node.js and TypeScript:**

Now that nvm is installed, you can use it to install Node.js and TypeScript. Here's how to install the latest LTS version of Node.js and TypeScript:

```bash
nvm install --lts
```

This command installs the latest LTS (Long Term Support) version of Node.js. Once Node.js is installed, you can install TypeScript using npm (Node Package Manager), which comes bundled with Node.js:

```bash
npm install -g typescript
```

This command installs TypeScript globally on your system.

**3. Verify the installations:**

You can verify that both Node.js and TypeScript have been installed by checking their versions:

```bash
node -v
npm -v
tsc -v
```

This should display the version numbers of Node.js, npm, and TypeScript.

That's it! You've successfully installed Node.js and TypeScript on your Ubuntu Linux system using nvm. You can now start developing TypeScript applications with Node.js.

#
_**If you want to switch to Node.js version 14 for your previous projects using Node Version Manager (nvm), you can follow these steps:**_

**1. Check available Node.js versions:**

To see the list of Node.js versions available for installation, you can use the following command:

```bash
nvm ls-remote
```

This will list all the available Node.js versions. You can look for version 14 in the list.

**2. Install Node.js version 14:**

To install Node.js version 14, use the following command, replacing "14" with the version you want:

```bash
nvm install 14
```

This will download and install Node.js version 14.

**3. Set Node.js version 14 as the default:**

To set Node.js version 14 as the default version for your projects, use the following command:

```bash
nvm use 14
```

This will switch your current shell session to use Node.js version 14. If you want to make it the default for all new shell sessions, you can run:

```bash
nvm alias default 14
```

Now, Node.js version 14 is the default version, and you can use it for your previous projects.

**4. Verify the Node.js version:**

You can verify that Node.js version 14 is in use by running:

```bash
node -v
```

This should display the version of Node.js, which should be 14.x.x if the installation was successful.

That's it! You've now switched to Node.js version 14 using nvm, and you can use it for your previous projects.

#
_**To switch back to Node.js version 20.9.0 or any other version you were using, you can use Node Version Manager (nvm). Here are the steps to switch to version 20.9.0:**_

1. List the available Node.js versions to see which versions are installed and available for use:

```bash
nvm ls
```

This will list the installed Node.js versions, and the currently active version will be indicated with an arrow.

2. To switch to Node.js version 20.9.0, use the following command, replacing "20.9.0" with the specific version you want:

```bash
nvm use 20.9.0
```

This command will set the active Node.js version to 20.9.0.

3. You can verify that you've switched to Node.js version 20.9.0 by running:

```bash
node -v
```

This should display the version number, which should be 20.9.0 if the switch was successful.

Now you are using Node.js version 20.9.0 for your projects. If you want to make this version the default for all new shell sessions, you can run:

```bash
nvm alias default 20.9.0
```

This will set version 20.9.0 as the default for new sessions.

You can use these commands to switch between different Node.js versions whenever you need to work on specific projects that require different Node.js versions.

============================================================

## 1-3 Write your first typescript program


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fuzzqy5o9gvja4e1wtqz.png)

> Typescript config file
: **tsc --init**
then we ill get a tsconfig.json file, then we will edit it:

1. search rootDir; then write typescritp file location in this rootDir

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kv7afzqdprwhxzi573t.png)

2. search outDir, write path of my typescript file will store in which location.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnnfvuids0rfjei5jx3c.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3mg9falp1hj3lcte6wo.png)

after that write tsc. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p73dhipd0egkpnius8u9.png)

## some extra package. to run typescript code directly
**1. Install ts-node-dev globally (recommended):** 

```
npm install -g ts-node-dev
```
**2. Use npx (without installing globally):**

```
ts-node-dev --respawn --transpile-only filelocation/filename.ts
```

```
npx ts-node-dev --respawn --transpile-only ./module1/src/index.ts

```
## 1-4 Basic data types

Certainly! Here are examples of various data types in TypeScript:

1. **Integer (int)**:

   ```typescript
   const age: number = 30;
   ```

2. **Floating-Point (float and double)**:

   ```typescript
   const pi: number = 3.14159;
   ```

3. **Boolean (bool)**:

   ```typescript
   const isTrue: boolean = true;
   ```

4. **Character (char)**:

   In TypeScript, characters are represented as single-character strings:

   ```typescript
   const firstLetter: string = "A";
   ```

5. **String**:

   ```typescript
   const greeting: string = "Hello, TypeScript!";
   ```

6. **Null**:

   ```typescript
   const nullValue: null = null;
   ```

7. **Undefined (or None)**:

   ```typescript
   let undefinedValue: undefined;
   ```

8. **Void**:

   Functions with no return value have a `void` type:

   ```typescript
   function sayHello(): void {
     console.log("Hello, world!");
   }
   ```

9. **Symbol**:

   ```typescript
   const uniqueSymbol: symbol = Symbol("description");
   ```

10. **Byte**:

    TypeScript doesn't have a specific byte data type, but you can work with bytes using `number` or `Uint8Array`.

11. **Date and Time**:

    TypeScript can work with date and time using JavaScript's `Date` object:

    ```typescript
    const currentDate: Date = new Date();
    ```

12. **BigInteger and BigDecimal**:

    TypeScript supports large integers through the `BigInt` type:

    ```typescript
    const bigIntValue: bigint = 1234567890123456789012345678901234567890n;
    ```

13. **Array**:

    Arrays in TypeScript can hold multiple values of the same data type:

    ```typescript
    const numbers: number[] = [1, 2, 3, 4, 5];
    ```

14. **Tuple**:

    Tuples allow you to specify the types and order of elements in a fixed-size collection:

    ```typescript
    const person: [string, number] = ["Alice", 30];
    ```

15. **Enum**:

    Enums define a set of named constant values:

    ```typescript
    enum Color {
      Red,
      Green,
      Blue,
    }

    const selectedColor: Color = Color.Red;
    ```

16. **Any**:

    The `any` type is used when you want to opt out of TypeScript's type checking or when dealing with dynamic types:

    ```typescript
    let dynamicValue: any = 42;
    dynamicValue = "Hello, World!";
    ```

17. **Union Types**:

    Union types allow variables to hold values of multiple types:

    ```typescript
    let mixedValue: number | string = 42;
    mixedValue = "Hello, World!";
    ```

18. **Intersection Types**:

    Intersection types combine multiple types into one, allowing access to properties of each type:

    ```typescript
    type Employee = { name: string; role: string };
    type Manager = { reports: number };
    type ManagerEmployee = Employee & Manager;
    const manager: ManagerEmployee = { name: "Alice", role: "Manager", reports: 5 };
    ```

19. **Object**:

    The `object` type represents non-primitive values, such as functions, arrays, and objects:

    ```typescript
    const user: object = { name: "Alice", age: 30 };
    ```

20. **Function**:

    Functions in TypeScript can be defined with specific parameter and return types:

    ```typescript
    const add: (x: number, y: number) => number = (x, y) => x + y;
    ```

These examples cover a wide range of basic data types and type annotations available in TypeScript. Each type has its own specific use cases, and TypeScript's strong type system helps catch type-related errors and improve code quality.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0nob7iinzp1bvecni40i.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9o0uh6m0xkli6zm4kxen.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ujcxn1qm8k6pmf82la56.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wubt1xrzffahisffppti.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/todj12qj6ae9gyfp9ckg.png)
----------------------------------------
In TypeScript, you can work with various basic data types, including:
These are the basic data types in TypeScript. Additionally, TypeScript supports more advanced types such as `object`, `any`, `void`, `null`, and `undefined`, as well as user-defined types like `enum`, `tuple`, and `union types` to handle a wide range of data in a strongly typed manner.

1. **Number**: Used for numeric values (integers and floating-point numbers).
   ```typescript
   let age: number = 30;
   let pi: number = 3.14;
   ```

2. **String**: Used for text and character data.
   ```typescript
   let name: string = "John";
   let message: string = 'Hello, TypeScript!';
   ```

3. **Boolean**: Represents true or false values.
   ```typescript
   let isStudent: boolean = true;
   let isWorking: boolean = false;
   ```

4. **Array**: Used to store collections of values, and you can specify the type of elements it contains.
   ```typescript
   let numbers: number[] = [1, 2, 3, 4, 5];
   let fruits: string[] = ["apple", "banana", "cherry"];
   ```
-----------------
## 1-5 Object , Optional and Literal
Here are examples of TypeScript data types and features related to objects, optional properties, and literals:

1. **Object Type**:

   TypeScript allows you to define object types to represent structured data with specific properties and their types.

   ```typescript
   const person: { name: string; age: number } = {
     name: "Alice",
     age: 30,
   };
   ```

2. **Optional Properties**:

   You can specify optional properties in object types using the `?` symbol.

   ```typescript
   const user: { name: string; age?: number } = {
     name: "Bob",
     // Age is optional, so it can be omitted
   };
   ```

3. **Literal Types**:

   TypeScript allows you to define literal types where a variable can only have a specific, literal value.

   ```typescript
   const status: "active" | "inactive" = "active";
   ```

4. **Object with Optional and Literal Properties**:

   You can combine object types, optional properties, and literal types.

   ```typescript
   const person: { name: string; age?: number; status: "active" | "inactive" } = {
     name: "Charlie",
     status: "active",
   };
   ```

5. **Type Alias**:

   You can create type aliases for object types to make your code more readable.

   ```typescript
   type Person = { name: string; age?: number };
   const user: Person = {
     name: "David",
     // Age is optional
   };
   ```

6. **Interface**:

   Interfaces are similar to type aliases but are often used when defining the shape of objects.

   ```typescript
   interface Product {
     name: string;
     price: number;
   }
   const item: Product = {
     name: "Widget",
     price: 10.99,
   };
   ```

7. **Record Type**:

   You can use the `Record` type to define object types with specific keys and their associated value types.

   ```typescript
   const phonebook: Record<string, string> = {
     Alice: "555-1234",
     Bob: "555-5678",
   };
   ```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fy97gdtb1gpkrdmf24cs.png)
=>Readonly property

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trxdeswqj92shcgre2c2.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9wvkzulb7rqnb95grnys.png)

## 1-6 Function in typescript

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lo6kz1ultrvx17v1scs.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4gc4fcej1dxynuwworp.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/armhcgny2rt11ifd9ocf.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s55mbxnpaa3i0850wxrc.png)

## 1-7 Spread and Rest Operator
Certainly! Here are examples of the spread and rest operators in TypeScript:

1. **Spread Operator**:

   The spread operator, denoted by `...`, is used to split an array or object into individual elements. It can be used to create new arrays or objects by combining existing ones.

   - **Array Spread**:

     ```typescript
     const arr1: number[] = [1, 2, 3];
     const arr2: number[] = [4, 5, 6];
     const combinedArray: number[] = [...arr1, ...arr2];
     ```

   - **Object Spread**:

     ```typescript
     const person = { name: "Alice", age: 30 };
     const additionalInfo = { city: "Wonderland" };
     const combinedPerson = { ...person, ...additionalInfo };
     ```

2. **Rest Operator**:

   The rest operator, also denoted by `...`, is used to collect multiple values into an array. It is often used in function parameters to handle a variable number of arguments.

   - **Rest Parameters in Functions**:

     ```typescript
     function sum(...numbers: number[]): number {
       return numbers.reduce((total, num) => total + num, 0);
     }

     const result1: number = sum(1, 2, 3, 4, 5); // Result: 15
     ```

   - **Rest Elements in Arrays**:

     ```typescript
     const [first, second, ...rest] = [1, 2, 3, 4, 5];
     console.log(first); // 1
     console.log(second); // 2
     console.log(rest); // [3, 4, 5]
     ```

{
typescript can acess all function globally. so we can use {bracket} in a ts file, then wont access same function globally.
}

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uvl1t1p4wbco9ikncuy9.png)



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hc04dgtlso947xz9uryf.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v2b016imzcuoa8n3gbf4.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e13bzrt5eohf131ubm67.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhzsl24epsi8byoy1dq6.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jk16986s25rs7iefzseq.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jxaxodww2ccdqdn80uvc.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjm6460p5vhsjbugbk4x.png)

## 1-8 Destructuring in typescript
Destructuring is a powerful feature in TypeScript that allows you to extract values from arrays and objects and assign them to variables. Here are examples of destructuring in TypeScript:

1. **Array Destructuring**:

   You can destructure arrays to extract individual values and assign them to variables:

   ```typescript
   const numbers: number[] = [1, 2, 3, 4, 5];

   const [first, second, ...rest] = numbers;

   console.log(first); // 1
   console.log(second); // 2
   console.log(rest); // [3, 4, 5]
   ```

2. **Object Destructuring**:

   Object destructuring allows you to extract properties from objects and assign them to variables with the same name:

   ```typescript
   const person = {
     name: "Alice",
     age: 30,
     city: "Wonderland",
   };

   const { name, age } = person;

   console.log(name); // "Alice"
   console.log(age); // 30
   ```

3. **Renaming Variables in Object Destructuring**:

   You can also rename variables while destructuring objects:

   ```typescript
   const person = {
     name: "Bob",
     age: 25,
   };

   const { name: fullName, age: years } = person;

   console.log(fullName); // "Bob"
   console.log(years); // 25
   ```

4. **Default Values in Object Destructuring**:

   You can provide default values for object properties that might not exist:

   ```typescript
   const person = {
     name: "Charlie",
   };

   const { name, age = 30 } = person;

   console.log(name); // "Charlie"
   console.log(age); // 30
   ```

5. **Nested Destructuring**:

   Destructuring can also be used with nested objects:

   ```typescript
   const student = {
     name: "David",
     details: {
       age: 21,
       major: "Computer Science",
     },
   };

   const { name, details: { age, major } } = student;

   console.log(name); // "David"
   console.log(age); // 21
   console.log(major); // "Computer Science"
   ```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hnrg9l1supwnejh7v1mz.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bk3l9ywpdwgc1uocp1oa.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nbmaa0m7f4fjyxqj3nc8.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bcz4078udoibz9afcx6a.png)

## ...rest

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czsbrxsxtdumxk1rly4b.png)

## 1-9 Type alias in typescript


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x41ykmgzsb607cbdjiir.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4qwjemrhkcmox75qqr46.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3f8ej8s2bnt9sxo1sbnm.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ls7b7jxj6diue24ucsdw.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mirhhxudof4p55nqtkgi.png)

## 1-10 Union and Intersection types

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2a0pm9kh0aohkpw9oko.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alfx80eql7iwu4nsw1it.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v25kr7vgas4no8785et1.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmjgwvw6zqtmarb218xb.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cyylf3vl0508vgjf8jyw.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j6x1cu9s562oatsykw8r.png)

## 1-11 Ternary, optional chaining & nullish coalescing operator

**1. nullish operator(??)** its works for Null and undefined. not for "" .
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ys683pqvg45my7v7nedm.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shxyjj1yyw2klu8chw2z.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/udqm9nmoq918nu1jltui.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rblftc0jde57koua7d9q.png)

## 1-12 Never,unknown and nullable type
Certainly! Here are examples of TypeScript data types and features related to `never`, `unknown`, and nullable types:

1. **`never` Type**:

   The `never` type represents values that never occur. It is often used to indicate that a function will never return normally or that a variable cannot have a value.

   ```typescript
   function throwError(message: string): never {
     throw new Error(message);
   }

   function infiniteLoop(): never {
     while (true) {
       // Infinite loop
     }
   }
   ```

2. **`unknown` Type**:

   The `unknown` type is a type-safe counterpart to `any`. Variables of type `unknown` can hold values of any type, but you must perform type checks before using them.

   ```typescript
   let userInput: unknown;
   let username: string;

   userInput = "Alice";
   if (typeof userInput === "string") {
     username = userInput;
   }
   ```

3. **Nullable Types**:

   TypeScript allows you to make a type nullable using the `null` and `undefined` values.

   ```typescript
   let numberOrNull: number | null = null;
   let stringOrUndefined: string | undefined = "Hello";
   ```

4. **Using `null` and `undefined` Together**:

   You can create a type that allows both `null` and `undefined` values.

   ```typescript
   let value: number | null | undefined = null;
   ```

5. **Type Assertion for `unknown`**:

   When working with `unknown`, you can use type assertions to tell TypeScript to treat a value as a specific type.

   ```typescript
   let userInput: unknown = "Bob";
   let username: string = userInput as string;
   ```

6. **Strict Null Checks**:

   TypeScript's strict null checks prevent variables from being used before being checked for null or undefined, reducing the risk of runtime errors.

   ```typescript
   let possiblyNull: string | null = null;
   // Error: Object is possibly 'null'.
   console.log(possiblyNull.length);
   ```

7. **Non-Nullable Assertion**:

   You can use the non-nullable assertion operator `!` to tell TypeScript that a value is not null or undefined.

   ```typescript
   let definitelyNotNull: string | null = "Carol";
   let length: number = definitelyNotNull!.length; // No error
   ```

These examples showcase TypeScript's `never`, `unknown`, and nullable types, which provide more control over types, safer code, and improved handling of optional and potentially missing values.
1. Nullable type
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ey8swlarvh5yis0mt9v.png)
2. unknown type
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pnl9qx2rbvkdyxbxnf3.png)
3.Never

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/md6vqkevus3ugy0bafiq.png)

##