├── .gitignore ├── Classes & Interfaces ├── Constructor Functions & The this Keyword.md ├── Getters & Setters.md ├── Inheritance.md ├── Overriding Properties & The protected Modifier.md ├── Private and Public Access Modifiers.md ├── README.md ├── Readonly Properties.md └── What are Classes.md ├── Getting Started ├── Installing & Using TypeScript.md ├── README.md ├── TypeScript Advantages.md └── What Is TypeScript & Why Should You Use It.md ├── Next-generation JavaScript & TypeScript ├── Array & Object Destructuring.md ├── Arrow Functions.md ├── Default Function Parameters.md ├── Let & Const.md ├── README.md ├── Rest Parameters.md └── The Spread Operator (…).md ├── README.md ├── TypeScript Basics & Basic Types ├── Arrays Type.md ├── Core Types & Concepts.md ├── Function Return Types & void”.md ├── Function Types & Callbacks.md ├── Functions & Types.md ├── Functions as Types.md ├── Literal Types.md ├── Nested Objects & Types.md ├── Object Types.md ├── README.md ├── The any Type.md ├── The never Type.md ├── The unknown Type.md ├── Type Aliases & Object Types.md ├── Type Aliases Custom Types.md ├── Type Assignment & Type Inference.md ├── Type Casing.md ├── TypeScript Types vs JavaScript Types.md ├── Understanding Types.md ├── Union Types.md ├── Using Types.md ├── Working with Enums.md ├── Working with Numbers, Strings & Booleans.md └── Working with Tuples.md ├── TypeScript Compiler ├── Compiling the Entire Project Multiple Files.md ├── Including & Excluding Files.md ├── Introduction.md ├── README.md ├── Setting a Compilation Target.md └── Understanding TypeScript Core Libs.md └── tscookbookcover.png /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store -------------------------------------------------------------------------------- /Classes & Interfaces/Constructor Functions & The this Keyword.md: -------------------------------------------------------------------------------- 1 | # Constructor Functions & The "this" Keyword 2 | 3 | ## Introduction 4 | 5 | Constructor functions in TypeScript are used to create and initialize objects based on a class. These functions are called when an instance of the class is created using the `new` keyword. The `this` keyword refers to the instance being created, allowing you to set and access properties specific to that instance. 6 | 7 | ## Example 8 | ```tsx 9 | class Person { 10 | // Properties 11 | name: string; 12 | age: number; 13 | 14 | // Constructor function 15 | constructor(name: string, age: number) { 16 | // Using the "this" keyword to refer to instance properties 17 | this.name = name; 18 | this.age = age; 19 | } 20 | 21 | // Method 22 | introduce(): string { 23 | return `Hello, my name is ${this.name} and I am ${this.age} years old.`; 24 | } 25 | } 26 | 27 | // Creating an instance of the class using the constructor 28 | const person1 = new Person("Alice", 25); 29 | 30 | // Accessing properties and calling methods 31 | console.log(person1.name); // Output: Alice 32 | console.log(person1.age); // Output: 25 33 | console.log(person1.introduce()); // Output: Hello, my name is Alice and I am 25 years old. 34 | ``` 35 | 36 | In this example: 37 | 38 | 1. The `Person` class has two properties, `name` and `age`, and a constructor function that initializes these properties when an instance is created. 39 | 2. Inside the constructor, `this` refers to the instance being created (e.g., `person1`). The properties `name` and `age` are assigned values specific to that instance. 40 | 3. The `introduce` method uses `this` to access the properties of the instance it is called on. 41 | 4. When `person1.introduce()` is called, the `this` keyword inside the `introduce` method refers to `person1`, and the method returns a string using the properties of that instance. 42 | 43 | It's important to note that the use of classes and constructor functions is a feature of ES6 (ECMAScript 2015) and later versions of JavaScript. TypeScript enhances this by providing static typing and additional features. 44 | 45 | In summary, constructor functions in TypeScript play a crucial role in initializing object instances by setting their properties using the `this` keyword. They contribute to creating organized and reusable code with class-based structures. -------------------------------------------------------------------------------- /Classes & Interfaces/Getters & Setters.md: -------------------------------------------------------------------------------- 1 | # Getters & Setters 2 | 3 | ## Introduction 4 | 5 | Getters and setters are special methods that allow you to control the access and modification of class properties. Getters are used to retrieve the value of a property, while setters are used to modify the value of a property. They provide a way to encapsulate the internal representation of an object and add behavior when getting or setting its properties. 6 | 7 | Here's an example demonstrating the use of getters and setters: 8 | 9 | ```tsx 10 | class Circle { 11 | private _radius: number; 12 | 13 | constructor(radius: number) { 14 | this._radius = radius; 15 | } 16 | 17 | // Getter for the radius property 18 | get radius(): number { 19 | console.log("Getting radius"); 20 | return this._radius; 21 | } 22 | 23 | // Setter for the radius property 24 | set radius(newRadius: number) { 25 | if (newRadius >= 0) { 26 | console.log("Setting radius"); 27 | this._radius = newRadius; 28 | } else { 29 | console.error("Radius must be a non-negative value"); 30 | } 31 | } 32 | 33 | // Getter for calculating the area 34 | get area(): number { 35 | console.log("Calculating area"); 36 | return Math.PI * this._radius ** 2; 37 | } 38 | } 39 | 40 | // Creating an instance of the class 41 | const myCircle = new Circle(5); 42 | 43 | // Using the getter to retrieve the radius 44 | console.log(myCircle.radius); // Output: Getting radius, 5 45 | 46 | // Using the setter to update the radius 47 | myCircle.radius = 8; // Output: Setting radius 48 | 49 | // Using the getter for calculating the area 50 | console.log(myCircle.area); // Output: Calculating area, 201.06192982974676 51 | 52 | // Attempting to set a negative radius (error message from the setter) 53 | myCircle.radius = -3; // Output: Radius must be a non-negative value 54 | ``` 55 | 56 | In this example: 57 | 58 | - The `Circle` class has a private property `_radius` and exposes it using a getter and setter. 59 | - The getter for `radius` allows retrieving the value of the `_radius` property with additional behavior (in this case, logging). 60 | - The setter for `radius` allows updating the value of `_radius` with validation logic to ensure the radius is non-negative. 61 | - A getter for `area` is included, demonstrating that getters can be used for computed properties. 62 | - The instance of `Circle` (`myCircle`) is created and accessed using the getter and setter. 63 | 64 | ### Use Cases: 65 | 66 | 1. **Encapsulation:** 67 | - Getters and setters provide a way to encapsulate the internal representation of an object, allowing controlled access to properties. 68 | 2. **Validation:** 69 | - Setters can include validation logic to ensure that property values meet certain criteria. 70 | 3. **Computed Properties:** 71 | - Getters can be used to calculate and return derived or computed properties based on other properties. 72 | 4. **Logging and Side Effects:** 73 | - Getters and setters can be used to log property access or modification and perform additional side effects. 74 | 5. **Property Access Control:** 75 | - Getters and setters allow you to control read and write access to properties, enabling fine-grained access control. 76 | 77 | By using getters and setters in TypeScript, you can design classes that provide a clean and controlled interface for accessing and modifying their properties, promoting encapsulation and maintaining the integrity of the object's state. -------------------------------------------------------------------------------- /Classes & Interfaces/Inheritance.md: -------------------------------------------------------------------------------- 1 | # Inheritance 2 | 3 | ## Introduction 4 | 5 | Inheritance is a mechanism that allows a class (called the derived or child class) to inherit properties and methods from another class (called the base or parent class). This promotes code reuse and the creation of hierarchies of related classes. The `extends` keyword is used to establish inheritance. 6 | 7 | ```tsx 8 | // Base class 9 | class Animal { 10 | // Properties 11 | name: string; 12 | 13 | // Constructor 14 | constructor(name: string) { 15 | this.name = name; 16 | } 17 | 18 | // Method 19 | makeSound(): string { 20 | return "Some generic sound"; 21 | } 22 | } 23 | 24 | // Derived class inheriting from Animal 25 | class Dog extends Animal { 26 | // Additional property 27 | breed: string; 28 | 29 | // Constructor 30 | constructor(name: string, breed: string) { 31 | // Calling the constructor of the base class using super() 32 | super(name); 33 | this.breed = breed; 34 | } 35 | 36 | // Overriding the makeSound method 37 | makeSound(): string { 38 | return "Woof!"; 39 | } 40 | 41 | // Additional method 42 | fetch(): string { 43 | return "Fetching the ball!"; 44 | } 45 | } 46 | 47 | // Creating an instance of the derived class 48 | const myDog = new Dog("Buddy", "Golden Retriever"); 49 | 50 | // Accessing inherited properties and methods 51 | console.log(myDog.name); // Output: Buddy 52 | console.log(myDog.makeSound()); // Output: Woof! 53 | console.log(myDog.fetch()); // Output: Fetching the ball! 54 | ``` 55 | 56 | In this example: 57 | 58 | - The `Animal` class is the base class, and the `Dog` class is the derived class. 59 | - The `Dog` class uses the `extends` keyword to inherit from the `Animal` class. 60 | - The `super` keyword is used in the constructor of the derived class to call the constructor of the base class and initialize inherited properties. 61 | - The `makeSound` method is overridden in the derived class, providing a specific implementation for dogs. 62 | - The `Dog` class introduces an additional property (`breed`) and an additional method (`fetch`). 63 | 64 | ### Access Modifiers in Inheritance: 65 | 66 | In TypeScript, access modifiers (`public`, `protected`, and `private`) can be used to control the visibility of members within a class and its subclasses: 67 | 68 | - `public`: Visible to everyone (default if not specified). 69 | - `protected`: Visible to the class and its subclasses. 70 | - `private`: Visible only within the class. 71 | 72 | ```tsx 73 | class Animal { 74 | private age: number; 75 | 76 | constructor(age: number) { 77 | this.age = age; 78 | } 79 | 80 | protected getAge(): number { 81 | return this.age; 82 | } 83 | } 84 | 85 | class Dog extends Animal { 86 | // The age property is not directly accessible here 87 | 88 | getDogAge(): number { 89 | // Accessing the protected method from the base class 90 | return this.getAge(); 91 | } 92 | } 93 | 94 | const myDog = new Dog(3); 95 | // Error: Property 'age' is private and only accessible within class 'Animal'. 96 | // console.log(myDog.age); 97 | 98 | // Accessing the protected method from the derived class 99 | console.log(myDog.getDogAge()); // Output: 3 100 | ``` 101 | 102 | ### Use Cases: 103 | 104 | - **Code Reusability:** 105 | - Inheritance allows the reuse of code from existing classes, reducing redundancy. 106 | - **Polymorphism:** 107 | - Derived classes can provide specific implementations for methods defined in the base class, allowing polymorphic behavior. 108 | - **Extending Functionality:** 109 | - Derived classes can extend the functionality of the base class by introducing new properties and methods. 110 | - **Creating Hierarchies:** 111 | - Inheritance is useful for creating class hierarchies, representing relationships between different types of objects. 112 | 113 | Inheritance is a powerful feature in TypeScript that enables the creation of more organized and reusable code by allowing classes to build upon the functionality of other classes. -------------------------------------------------------------------------------- /Classes & Interfaces/Overriding Properties & The protected Modifier.md: -------------------------------------------------------------------------------- 1 | # Overriding Properties & The "protected" Modifier 2 | 3 | ## Introduction 4 | 5 | When you extend a class and override its methods or properties, you can use the `protected` modifier to control access to those members. The `protected` modifier allows the member to be accessed within the class and its subclasses but not from external code. 6 | 7 | Here's an example demonstrating property overriding and the use of the `protected` modifier: 8 | 9 | ```tsx 10 | // Base class 11 | class Animal { 12 | // Protected property 13 | protected sound: string; 14 | 15 | // Constructor 16 | constructor(sound: string) { 17 | this.sound = sound; 18 | } 19 | 20 | // Method 21 | makeSound(): string { 22 | return this.sound; 23 | } 24 | } 25 | 26 | // Derived class inheriting from Animal 27 | class Dog extends Animal { 28 | // Constructor with additional parameter 29 | constructor(sound: string, private breed: string) { 30 | // Calling the constructor of the base class using super() 31 | super(sound); 32 | } 33 | 34 | // Overriding the makeSound method 35 | makeSound(): string { 36 | // Accessing the protected property from the base class 37 | const baseSound = super.makeSound(); 38 | 39 | // Adding breed information 40 | return `${baseSound} (Breed: ${this.breed})`; 41 | } 42 | } 43 | 44 | // Creating an instance of the derived class 45 | const myDog = new Dog("Woof", "Golden Retriever"); 46 | 47 | // Accessing overridden method 48 | console.log(myDog.makeSound()); // Output: Woof (Breed: Golden Retriever) 49 | 50 | // Accessing the protected property from the base class is not allowed externally 51 | // Error: Property 'sound' is protected and only accessible within class 'Animal' and its subclasses. 52 | // console.log(myDog.sound); 53 | ``` 54 | 55 | In this example: 56 | 57 | - The `Animal` class has a `protected` property `sound`. This property is accessible within the class and its subclasses but not externally. 58 | - The `Dog` class extends `Animal` and overrides the `makeSound` method. It uses the `super` keyword to call the overridden method from the base class. 59 | - The `Dog` class has an additional private property (`breed`), and the `makeSound` method combines the base sound with the breed information. 60 | - The `sound` property from the base class is not directly accessible from external code. 61 | 62 | ### Use Cases: 63 | 64 | 1. **Overriding Methods:** 65 | - The `protected` modifier is often used when overriding methods to allow subclasses to access and modify certain aspects of the behavior. 66 | 2. **Extending Functionality:** 67 | - Subclasses can add additional properties or methods while building upon the functionality of the base class. 68 | 3. **Encapsulation:** 69 | - Using `protected` helps encapsulate the internal details of a class and provides controlled access to its members. 70 | 4. **Polymorphism:** 71 | - Overriding methods and properties enables polymorphic behavior, allowing different classes to be used interchangeably. 72 | 73 | In summary, the `protected` modifier in TypeScript is useful when designing class hierarchies and allows for controlled access to properties and methods within a class and its subclasses. This promotes encapsulation and supports the principles of object-oriented programming. -------------------------------------------------------------------------------- /Classes & Interfaces/Private and Public Access Modifiers.md: -------------------------------------------------------------------------------- 1 | # "Private" and "Public" Access Modifiers 2 | 3 | ## Introduction 4 | 5 | Access modifiers in TypeScript, such as `private` and `public`, are used to control the visibility of class members (properties and methods) within a class and its subclasses. They help enforce encapsulation and define how properties and methods can be accessed from outside the class. 6 | 7 | ### `Private` Access Modifier: 8 | 9 | When a class member is marked as `private`, it can only be accessed within the class where it is defined. It is not accessible from outside the class, including from instances of the class or its subclasses. 10 | 11 | ```tsx 12 | class Car { 13 | private speed: number; 14 | 15 | constructor(speed: number) { 16 | this.speed = speed; 17 | } 18 | 19 | accelerate(increment: number): void { 20 | this.speed += increment; 21 | } 22 | 23 | displaySpeed(): void { 24 | console.log(`Current speed: ${this.speed} km/h`); 25 | } 26 | } 27 | 28 | // Creating an instance of the class 29 | const myCar = new Car(50); 30 | 31 | // Accessing a private member will result in a TypeScript compilation error 32 | // Uncommenting the line below will result in an error: 33 | // myCar.speed = 60; 34 | 35 | // Calling public methods is allowed 36 | myCar.accelerate(10); 37 | myCar.displaySpeed(); // Output: Current speed: 60 km/h 38 | ``` 39 | 40 | In this example, the `speed` property is marked as `private`, making it inaccessible from outside the `Car` class. 41 | 42 | ### `public` Access Modifier: 43 | 44 | By default, class members are considered `public` if no access modifier is specified. `public` members are accessible from outside the class. 45 | 46 | ```tsx 47 | class Animal { 48 | // By default, "legs" is public 49 | legs: number; 50 | 51 | constructor(legs: number) { 52 | this.legs = legs; 53 | } 54 | 55 | displayLegs(): void { 56 | console.log(`Number of legs: ${this.legs}`); 57 | } 58 | } 59 | 60 | // Creating an instance of the class 61 | const dog = new Animal(4); 62 | 63 | // Accessing public members is allowed 64 | dog.legs = 3; // Allowed 65 | dog.displayLegs(); // Output: Number of legs: 3 66 | ``` 67 | 68 | In this example, the `legs` property is implicitly `public`, and it can be accessed and modified from outside the `Animal` class. 69 | 70 | ### Use Cases: 71 | 72 | - **`private` Access Modifier:** 73 | - Use `private` for class members that should not be accessible from outside the class. This helps encapsulate internal details and prevents external interference. 74 | - **`public` Access Modifier:** 75 | - By default, members are `public`, and this is suitable for properties and methods that need to be accessed externally. 76 | - **Encapsulation:** 77 | - Access modifiers contribute to encapsulation by controlling the visibility of class members, improving code organization and maintainability. 78 | 79 | By using `private` and `public` access modifiers appropriately, you can design classes with a clear and controlled interface, enhancing the maintainability and robustness of your TypeScript code. -------------------------------------------------------------------------------- /Classes & Interfaces/README.md: -------------------------------------------------------------------------------- 1 | # Classes & Interfaces 2 | 3 | ## Introduction 4 | 5 | Classes serve as blueprints for creating objects, allowing for better organization and encapsulation of data and behavior. Interfaces, on the other hand, define contracts for classes to adhere to, promoting code reuse and ensuring consistency. Explore the topics below to gain a comprehensive understanding of Classes & Interfaces in TypeScript. 6 | 7 | ## Table of Contents 8 | 9 | - [What are Classes?](./What%20are%20Classes.md) 10 | - [Constructor Functions & The "this" Keyword](./Constructor%20Functions%20&%20The%20this%20Keyword.md) 11 | - ["Private" and "Public" Access Modifiers](./Private%20and%20Public%20Access%20Modifiers.md) 12 | - ["Readonly" Properties](./Readonly%20Properties.md) 13 | - [Inheritance](./Inheritance.md) 14 | - [Overriding Properties & The "protected" Modifier](./Overriding%20Properties%20&%20The%20protected%20Modifier.md) 15 | - [Getters & Setters](./Getters%20&%20Setters.md) -------------------------------------------------------------------------------- /Classes & Interfaces/Readonly Properties.md: -------------------------------------------------------------------------------- 1 | # "Readonly" Properties 2 | 3 | ## Introduction 4 | 5 | The `readonly` keyword is used to make class properties or object properties immutable after their initial assignment. Once a property is marked as `readonly`, its value cannot be changed. This ensures that the property remains constant throughout the object's or class instance's lifetime. 6 | 7 | ```tsx 8 | class Circle { 9 | // Readonly properties 10 | readonly radius: number; 11 | 12 | // Readonly properties can be initialized in the constructor 13 | constructor(radius: number) { 14 | this.radius = radius; 15 | } 16 | 17 | // Readonly properties cannot be reassigned 18 | updateRadius(newRadius: number): void { 19 | // Error: Cannot assign to 'radius' because it is a read-only property. 20 | // this.radius = newRadius; 21 | } 22 | 23 | // Readonly properties can be accessed 24 | calculateArea(): number { 25 | return Math.PI * this.radius * this.radius; 26 | } 27 | } 28 | 29 | // Creating an instance of the class 30 | const myCircle = new Circle(5); 31 | 32 | // Accessing readonly properties 33 | console.log(myCircle.radius); // Output: 5 34 | 35 | // Readonly properties cannot be modified after initialization 36 | // Error: Cannot assign to 'radius' because it is a read-only property. 37 | // myCircle.radius = 10; 38 | ``` 39 | 40 | In this example: 41 | 42 | - The `Circle` class has a `readonly` property `radius`. 43 | - The `readonly` property is initialized in the constructor and cannot be reassigned afterward. 44 | - An attempt to modify the `readonly` property after initialization results in a compilation error. 45 | 46 | ### Readonly Modifiers with Parameters: 47 | 48 | You can also use `readonly` in constructor parameters to automatically create and initialize `readonly` properties: 49 | 50 | ```tsx 51 | class Rectangle { 52 | // Automatically created and initialized readonly properties 53 | constructor(readonly width: number, readonly height: number) {} 54 | 55 | // Readonly properties can be accessed 56 | calculateArea(): number { 57 | return this.width * this.height; 58 | } 59 | } 60 | 61 | // Creating an instance of the class 62 | const myRectangle = new Rectangle(4, 6); 63 | 64 | // Accessing readonly properties 65 | console.log(myRectangle.width); // Output: 4 66 | console.log(myRectangle.height); // Output: 6 67 | 68 | // Readonly properties cannot be modified after initialization 69 | // Error: Cannot assign to 'width' because it is a read-only property. 70 | // myRectangle.width = 8; 71 | ``` 72 | 73 | In this example, the `width` and `height` properties are automatically created and initialized as `readonly` based on the `readonly` modifier in the constructor parameters. 74 | 75 | ### Use Cases: 76 | 77 | 1. **Immutable Configuration:** 78 | - When certain properties of an object or class should remain constant throughout its lifecycle. 79 | 2. **Preventing Accidental Modifications:** 80 | - To avoid unintended modifications to critical properties. 81 | 3. **Documentation of Intent:** 82 | - Clearly indicating that a property is intended to be read-only in the code, making the code more self-explanatory. 83 | 4. **Constructor Initialization:** 84 | - Automatically creating and initializing read-only properties based on constructor parameters. 85 | 86 | Using `readonly` properties in TypeScript provides a way to enforce immutability for specific properties, promoting safer and more predictable code. -------------------------------------------------------------------------------- /Classes & Interfaces/What are Classes.md: -------------------------------------------------------------------------------- 1 | # What are Classes? 2 | 3 | ## Introduction 4 | 5 | Classes are a fundamental component of object-oriented programming (OOP) that provide a blueprint for creating objects with shared properties and behaviors. TypeScript adds static typing to the class-based OOP features of JavaScript. 6 | 7 | ### Basic Class Syntax: 8 | 9 | ```tsx 10 | class Animal { 11 | // Properties 12 | name: string; 13 | age: number; 14 | 15 | // Constructor 16 | constructor(name: string, age: number) { 17 | this.name = name; 18 | this.age = age; 19 | } 20 | 21 | // Method 22 | makeSound(): string { 23 | return "Some generic sound"; 24 | } 25 | } 26 | 27 | // Creating an instance of the class 28 | const myPet = new Animal("Fluffy", 3); 29 | 30 | // Accessing properties and calling methods 31 | console.log(myPet.name); // Output: Fluffy 32 | console.log(myPet.age); // Output: 3 33 | console.log(myPet.makeSound()); // Output: Some generic sound 34 | ``` 35 | 36 | ### Key Concepts: 37 | 38 | 1. **Class Declaration:** 39 | - Classes are declared using the `class` keyword followed by the class name. 40 | 2. **Properties:** 41 | - Class properties are variables that hold data associated with the class. 42 | 3. **Constructor:** 43 | - The `constructor` method is a special method that is called when an object is created from the class. It is used to initialize object properties. 44 | 4. **Methods:** 45 | - Class methods are functions associated with the class and can be called on instances of the class. 46 | 5. **Instance Creation:** 47 | - Instances of a class are created using the `new` keyword, followed by the class name and constructor arguments. 48 | 6. **Access Modifiers:** 49 | - TypeScript supports access modifiers (`public`, `private`, and `protected`) to control the visibility of properties and methods. 50 | 51 | ### Inheritance: 52 | 53 | Classes in TypeScript can inherit properties and methods from other classes through inheritance. Here's an example: 54 | 55 | ```tsx 56 | class Dog extends Animal { 57 | // Additional property 58 | breed: string; 59 | 60 | // Constructor 61 | constructor(name: string, age: number, breed: string) { 62 | super(name, age); // Calling the constructor of the base class 63 | this.breed = breed; 64 | } 65 | 66 | // Overriding the makeSound method 67 | makeSound(): string { 68 | return "Woof!"; 69 | } 70 | 71 | // Additional method 72 | fetch(): string { 73 | return "Fetching the ball!"; 74 | } 75 | } 76 | 77 | // Creating an instance of the derived class 78 | const myDog = new Dog("Buddy", 2, "Golden Retriever"); 79 | 80 | // Accessing inherited properties and methods 81 | console.log(myDog.name); // Output: Buddy 82 | console.log(myDog.age); // Output: 2 83 | console.log(myDog.makeSound()); // Output: Woof! 84 | console.log(myDog.fetch()); // Output: Fetching the ball! 85 | ``` 86 | 87 | ### TypeScript vs. JavaScript: 88 | 89 | While classes are part of ES6 and are supported in modern JavaScript, TypeScript enhances class-based programming by providing static typing, interfaces, abstract classes, and other features that enable more robust and maintainable code. 90 | 91 | In summary, classes in TypeScript are a way to create reusable, object-oriented code with the added benefits of static typing and other language features. They help structure code in a modular and organized manner. -------------------------------------------------------------------------------- /Getting Started/Installing & Using TypeScript.md: -------------------------------------------------------------------------------- 1 | # Installing & Using TypeScript 2 | 3 | To install and use TypeScript, you can follow these steps: 4 | 5 | ### Installation: 6 | 7 | 1. **Install Node.js:** 8 | - TypeScript requires Node.js and npm (Node Package Manager). You can download and install them from the official website: [Node.js](https://nodejs.org/) 9 | 2. **Install TypeScript globally:** 10 | - Open your terminal or command prompt and run the following command to install TypeScript globally: 11 | This command installs the TypeScript compiler globally on your machine. 12 | 13 | ```bash 14 | npm install -g typescript 15 | ``` 16 | 17 | 18 | ### Using TypeScript: 19 | 20 | 1. **Create a TypeScript File:** 21 | - Create a new file with a `.ts` extension. For example, `app.ts`. 22 | 2. **Write TypeScript Code:** 23 | - Write your TypeScript code in the `.ts` file. TypeScript supports JavaScript syntax along with additional features. For example: 24 | 25 | ```tsx 26 | // app.ts 27 | function greeter(person: string) { 28 | return "Hello, " + person; 29 | } 30 | 31 | let user = "John"; 32 | console.log(greeter(user)); 33 | ``` 34 | 35 | 3. **Compile TypeScript Code:** 36 | - Compile the TypeScript code into JavaScript using the TypeScript compiler. Run the following command in the terminal: 37 | This command generates a corresponding `.js` file. In this case, `app.js`. 38 | 39 | ```bash 40 | tsc app.ts 41 | ``` 42 | 43 | 4. **Run the JavaScript Code:** 44 | - You can now run the generated JavaScript code using Node.js. For example: 45 | This will execute the JavaScript code produced by the TypeScript compiler. 46 | 47 | ```bash 48 | node app.js 49 | ``` 50 | 51 | 52 | ### Configuration (Optional): 53 | 54 | - You can create a `tsconfig.json` file in your project to configure TypeScript settings. This file allows you to specify compiler options, include/exclude files, and more. Here's a basic example: 55 | 56 | ```json 57 | { 58 | "compilerOptions": { 59 | "target": "es5", 60 | "module": "commonjs", 61 | "strict": true 62 | } 63 | } 64 | ``` 65 | 66 | - After creating a `tsconfig.json` file, you can compile your TypeScript code by simply running `tsc` in the terminal. The compiler will use the configuration settings defined in `tsconfig.json`. 67 | 68 | That's it! You've successfully installed TypeScript and created a simple TypeScript project. You can now continue writing and compiling TypeScript code based on your project needs. -------------------------------------------------------------------------------- /Getting Started/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ## Introduction 4 | 5 | Welcome to the Getting Started guide! 6 | 7 | Explore TypeScript fundamentals, installation, and advantages in this concise resource. 8 | 9 | ## Table of Contents 10 | 11 | - [What Is TypeScript & Why Should You Use It?](./What%20Is%20TypeScript%20&%20Why%20Should%20You%20Use%20It.md) 12 | - [Installing & Using TypeScript](./Installing%20&%20Using%20TypeScript.md) 13 | - [TypeScript Advantages](./TypeScript%20Advantages.md) 14 | -------------------------------------------------------------------------------- /Getting Started/TypeScript Advantages.md: -------------------------------------------------------------------------------- 1 | # TypeScript Advantages 2 | 3 | TypeScript offers several advantages over traditional JavaScript, making it a popular choice for many developers. Here are some key advantages of TypeScript: 4 | 5 | 1. **Static Typing:** 6 | - TypeScript introduces static typing, allowing developers to define types for variables, function parameters, and return values. This helps catch errors during development and enhances the robustness and reliability of the code. 7 | 2. **Enhanced Tooling and IDE Support:** 8 | - Static typing enables better tooling and Integrated Development Environment (IDE) support. Tools like autocompletion, intelligent code navigation, and error checking become more effective, leading to increased developer productivity. 9 | 3. **Improved Code Maintainability:** 10 | - Static types make the code more readable and maintainable. Developers can better understand the expected data types and structures of variables and functions, leading to a reduction in errors and facilitating collaboration among team members. 11 | 4. **ECMAScript Compatibility:** 12 | - TypeScript is designed to be compatible with ECMAScript standards. This means that valid JavaScript code is also valid TypeScript code, allowing developers to use existing JavaScript libraries and gradually adopt TypeScript into projects. 13 | 5. **Object-Oriented Features:** 14 | - TypeScript supports object-oriented programming concepts such as classes, interfaces, and inheritance. This facilitates the development of more organized and structured code, especially in larger projects where object-oriented design patterns are beneficial. 15 | 6. **Compile-Time Checking:** 16 | - TypeScript code is transpiled into JavaScript before execution. The TypeScript compiler performs static analysis and checks for errors during this transpilation process. This helps catch potential issues early in the development process. 17 | 7. **Community and Ecosystem:** 18 | - TypeScript has gained significant popularity, and there is a thriving community supporting its development. Many popular JavaScript libraries and frameworks include TypeScript typings, making it easier to integrate TypeScript into various projects. 19 | 8. **Backward Compatibility:** 20 | - TypeScript is a superset of JavaScript, meaning existing JavaScript code can be gradually migrated to TypeScript. Developers can start using TypeScript features incrementally and refactor parts of their codebase as needed. 21 | 9. **Enhanced Readability with JSDoc:** 22 | - TypeScript supports JSDoc comments, which allow developers to add type information to regular JavaScript code. This is especially useful when working with existing JavaScript codebases, providing a way to gradually introduce TypeScript typing. 23 | 10. **Strong IDE Support:** 24 | - TypeScript has strong support in popular IDEs like Visual Studio Code. This includes features like autocompletion, intelligent code navigation, and inline documentation, enhancing the development experience. 25 | 26 | Overall, TypeScript provides a set of features and tools that contribute to better code quality, maintainability, and developer efficiency, particularly in larger and more complex projects. -------------------------------------------------------------------------------- /Getting Started/What Is TypeScript & Why Should You Use It.md: -------------------------------------------------------------------------------- 1 | # What Is TypeScript & Why Should You Use It? 2 | 3 | TypeScript is a superset of JavaScript, meaning it extends and adds features to JavaScript. It is designed for the development of large-scale applications and aims to make it easier to write and maintain complex codebases. Here are some key aspects of TypeScript and reasons why you might consider using it: 4 | 5 | 1. **Static Typing:** 6 | - TypeScript introduces static typing to JavaScript. This means that you can define types for variables, function parameters, and return values. Static typing helps catch errors during development, providing a level of code quality and reliability that is not inherent in standard JavaScript. 7 | 2. **Enhanced Tooling and IDE Support:** 8 | - With static typing, TypeScript enables better tooling and IDE support. Integrated Development Environments (IDEs) like Visual Studio Code can provide more accurate autocompletion suggestions, error checking, and refactoring tools, making the development process more efficient. 9 | 3. **Improved Code Maintainability:** 10 | - The addition of static types can enhance code readability and maintainability. Developers can understand the expected data types and structure of variables and functions more easily, making the codebase less prone to errors and facilitating collaboration among team members. 11 | 4. **ECMAScript Compatibility:** 12 | - TypeScript is designed to be compatible with ECMAScript, the standard upon which JavaScript is based. This means that valid JavaScript code is also valid TypeScript code, allowing developers to gradually adopt TypeScript into existing projects or use existing JavaScript libraries without modification. 13 | 5. **Object-Oriented Features:** 14 | - TypeScript supports object-oriented programming concepts such as classes, interfaces, and inheritance. This can lead to more organized and structured code, especially in larger projects where object-oriented design patterns are beneficial. 15 | 6. **Compile-Time Checking:** 16 | - TypeScript code is transpiled into JavaScript before execution. The TypeScript compiler performs static analysis and checks for errors during this transpilation process. This allows developers to catch potential issues early, before the code is run, providing an additional layer of safety. 17 | 7. **Community and Ecosystem:** 18 | - TypeScript has gained significant popularity, and there is a vibrant community supporting its development. Many popular JavaScript libraries and frameworks include TypeScript typings, making it easier to integrate TypeScript into various projects. 19 | 8. **Backward Compatibility:** 20 | - As TypeScript is a superset of JavaScript, existing JavaScript code can be gradually migrated to TypeScript. You can start using TypeScript features incrementally and refactor parts of your codebase as needed. 21 | 22 | In summary, TypeScript offers static typing, enhanced tooling, improved code maintainability, and object-oriented features, making it a valuable choice for building robust and scalable applications, especially in larger development projects. 23 | -------------------------------------------------------------------------------- /Next-generation JavaScript & TypeScript/Array & Object Destructuring.md: -------------------------------------------------------------------------------- 1 | # Array & Object Destructuring 2 | 3 | Array and object destructuring are features introduced in ECMAScript 6 (ES6) and are supported in both JavaScript and TypeScript. They provide a concise syntax for extracting values from arrays and objects, making code more readable and enabling a more expressive programming style. 4 | 5 | ### Array Destructuring: 6 | 7 | ### 1. **Basic Syntax:** 8 | 9 | ```jsx 10 | const numbers = [1, 2, 3, 4, 5]; 11 | const [first, second, third] = numbers; 12 | 13 | console.log(first); // Output: 1 14 | console.log(second); // Output: 2 15 | console.log(third); // Output: 3 16 | ``` 17 | 18 | ### 2. **Skipping Elements:** 19 | 20 | You can skip elements by leaving empty spaces in the destructuring pattern. 21 | 22 | ```jsx 23 | const [first, , third] = numbers; 24 | ``` 25 | 26 | ### 3. **Rest Parameter:** 27 | 28 | Use the rest parameter (`...`) to capture remaining elements into an array. 29 | 30 | ```jsx 31 | const [first, ...rest] = numbers; 32 | ``` 33 | 34 | ### Object Destructuring: 35 | 36 | ### 1. **Basic Syntax:** 37 | 38 | ```jsx 39 | const person = { name: 'John', age: 30, city: 'New York' }; 40 | const { name, age, city } = person; 41 | 42 | console.log(name); // Output: John 43 | console.log(age); // Output: 30 44 | console.log(city); // Output: New York 45 | ``` 46 | 47 | ### 2. **Renaming Variables:** 48 | 49 | You can rename variables during destructuring. 50 | 51 | ```jsx 52 | const { name: fullName, age: userAge } = person; 53 | ``` 54 | 55 | ### 3. **Default Values:** 56 | 57 | Provide default values for variables in case the property is undefined. 58 | 59 | ```jsx 60 | const { name, age, city = 'Unknown' } = person; 61 | ``` 62 | 63 | ### Destructuring in TypeScript: 64 | 65 | ### 1. **Array Destructuring in TypeScript:** 66 | 67 | ```tsx 68 | const numbers: number[] = [1, 2, 3, 4, 5]; 69 | const [first, second, third]: number[] = numbers; 70 | ``` 71 | 72 | ### 2. **Object Destructuring in TypeScript:** 73 | 74 | ```tsx 75 | interface Person { 76 | name: string; 77 | age: number; 78 | city: string; 79 | } 80 | 81 | const person: Person = { name: 'John', age: 30, city: 'New York' }; 82 | const { name, age, city }: Person = person; 83 | ``` 84 | 85 | ### 3. **Function Parameter Destructuring in TypeScript:** 86 | 87 | Destructuring in function parameters is commonly used in TypeScript. 88 | 89 | ```tsx 90 | function printPersonInfo({ name, age, city }: Person): void { 91 | console.log(`Name: ${name}, Age: ${age}, City: ${city}`); 92 | } 93 | ``` 94 | 95 | ### Use Cases: 96 | 97 | - **Simplified Variable Assignment:** 98 | Destructuring allows you to assign values to variables more conveniently, especially when dealing with arrays or objects. 99 | 100 | ```tsx 101 | const numbers: number[] = [1, 2, 3]; 102 | const [first, second, third]: number[] = numbers; 103 | ``` 104 | 105 | - **Parameter Passing in Functions:** 106 | Destructuring parameters in functions can make function calls more expressive. 107 | 108 | ```tsx 109 | function printPersonInfo({ name, age, city }: Person): void { 110 | console.log(`Name: ${name}, Age: ${age}, City: ${city}`); 111 | } 112 | ``` 113 | 114 | - **Object Property Renaming:** 115 | Renaming variables during destructuring can be useful when dealing with external data. 116 | 117 | ```tsx 118 | const { name: fullName, age: userAge }: Person = person; 119 | ``` 120 | 121 | - **Default Values:** 122 | Destructuring with default values is helpful when handling properties that may be undefined. 123 | 124 | ```tsx 125 | const { name, age, city = 'Unknown' }: Person = person; 126 | ``` 127 | 128 | 129 | Array and object destructuring enhance code readability and provide a concise syntax for working with arrays and objects. They are widely used in modern JavaScript and TypeScript programming. -------------------------------------------------------------------------------- /Next-generation JavaScript & TypeScript/Arrow Functions.md: -------------------------------------------------------------------------------- 1 | # Arrow Functions 2 | 3 | Arrow functions, introduced in ECMAScript 6 (ES6) and supported in both JavaScript and TypeScript, provide a concise syntax for writing functions. Arrow functions are particularly useful for short, anonymous functions and have some key differences compared to traditional function expressions. Here's an overview of arrow functions: 4 | 5 | ### Arrow Functions in JavaScript: 6 | 7 | 1. **Syntax:** 8 | 9 | ```jsx 10 | // Traditional Function Expression 11 | let add = function (a, b) { 12 | return a + b; 13 | }; 14 | 15 | // Arrow Function 16 | let addArrow = (a, b) => a + b; 17 | ``` 18 | 19 | 2. **Conciseness:** 20 | Arrow functions offer a shorter syntax, especially for simple functions with a single expression. If the function has only one statement, you can omit the curly braces and the `return` keyword. 21 | 3. **Lexical `this`:** 22 | One significant difference is that arrow functions do not have their own `this` context. Instead, they inherit `this` from the enclosing scope. Traditional functions, on the other hand, have their own `this` context, which can be a source of confusion. 23 | 24 | ```jsx 25 | function Person() { 26 | this.age = 0; 27 | 28 | setInterval(function growUp() { 29 | // In a traditional function, `this` refers to the global object (e.g., window in browsers) 30 | this.age++; 31 | }, 1000); 32 | } 33 | 34 | // Using an arrow function to maintain the outer `this` 35 | function Person() { 36 | this.age = 0; 37 | 38 | setInterval(() => { 39 | // In an arrow function, `this` refers to the `this` value of the enclosing scope 40 | this.age++; 41 | }, 1000); 42 | } 43 | ``` 44 | 45 | 46 | ### Arrow Functions in TypeScript: 47 | 48 | 1. **Syntax:** 49 | TypeScript supports arrow functions with the same syntax as JavaScript. Additionally, you can add type annotations for parameters and return types. 50 | 51 | ```tsx 52 | // Arrow Function with Type Annotations 53 | let addArrow: (a: number, b: number) => number = (a, b) => a + b; 54 | 55 | ``` 56 | 57 | 2. **Type Inference:** 58 | TypeScript can often infer the types of parameters and the return type based on the context. If the function body is a single expression, TypeScript can infer the return type. 59 | 60 | ```tsx 61 | // Type Inference for Arrow Function 62 | let addArrow = (a: number, b: number) => a + b; 63 | ``` 64 | 65 | 3. **Lexical Scoping with `this`:** 66 | The lexical scoping behavior of arrow functions in TypeScript is beneficial for maintaining the correct `this` context. 67 | 68 | ```tsx 69 | class Person { 70 | age: number = 0; 71 | 72 | // Arrow Function maintains the outer `this` 73 | growUp = () => { 74 | this.age++; 75 | }; 76 | } 77 | 78 | let person = new Person(); 79 | setInterval(person.growUp, 1000); 80 | ``` 81 | 82 | 83 | ### Use Cases: 84 | 85 | - **Short, Simple Functions:** 86 | Arrow functions are well-suited for short and simple functions, especially when brevity is desired. 87 | - **Avoiding `this` Confusion:** 88 | Arrow functions can help avoid issues with `this` in certain scenarios, as they don't have their own `this` context. 89 | - **Callback Functions:** 90 | Arrow functions are often used for callback functions and in functional programming constructs. 91 | - **Concise Syntax:** 92 | When the concise syntax of arrow functions improves code readability. 93 | 94 | Overall, arrow functions in TypeScript offer a concise and convenient syntax for defining functions, and their lexical scoping behavior can help mitigate issues related to `this` in certain contexts. -------------------------------------------------------------------------------- /Next-generation JavaScript & TypeScript/Default Function Parameters.md: -------------------------------------------------------------------------------- 1 | # Default Function Parameters 2 | 3 | Default function parameters, introduced in ECMAScript 6 (ES6) and supported in both JavaScript and TypeScript, allow you to specify default values for function parameters. This feature provides a more concise way to handle optional parameters and ensures that a function can still be called successfully even if some parameters are not provided. 4 | 5 | ### Default Function Parameters in JavaScript: 6 | 7 | 1. **Syntax:** 8 | 9 | ```jsx 10 | // ES6 Default Parameter Syntax 11 | function greet(name = "Guest", greeting = "Hello") { 12 | console.log(`${greeting}, ${name}!`); 13 | } 14 | 15 | // Calling the function without providing parameters 16 | greet(); // Output: Hello, Guest! 17 | 18 | // Calling the function with provided parameters 19 | greet("John", "Hi"); // Output: Hi, John! 20 | ``` 21 | 22 | 2. **Positional Defaults:** 23 | Default parameters are positional, meaning that if a default value is specified for a parameter, all subsequent parameters must also have default values. 24 | 25 | ```jsx 26 | // Valid: Defaults are provided for both parameters 27 | function example(a = 1, b = 2) { 28 | // Function body 29 | } 30 | 31 | // Invalid: If a default is provided for 'b', a default must be provided for 'a' as well 32 | function invalidExample(a, b = 2) { 33 | // Function body 34 | } 35 | ``` 36 | 37 | 38 | ### Default Function Parameters in TypeScript: 39 | 40 | 1. **Syntax:** 41 | In TypeScript, default parameters work similarly to JavaScript. You can specify default values and optionally include type annotations. 42 | 43 | ```tsx 44 | // TypeScript Default Parameter Syntax 45 | function greet(name: string = "Guest", greeting: string = "Hello"): void { 46 | console.log(`${greeting}, ${name}!`); 47 | } 48 | ``` 49 | 50 | 2. **Type Annotations:** 51 | TypeScript allows you to include type annotations for default parameters to enforce the expected types. 52 | 53 | ```tsx 54 | // TypeScript Default Parameter with Type Annotations 55 | function add(a: number, b: number = 0): number { 56 | return a + b; 57 | } 58 | ``` 59 | 60 | 3. **Rest Parameters and Default Values:** 61 | You can use rest parameters (`...rest`) along with default values to handle an arbitrary number of additional parameters. 62 | 63 | ```tsx 64 | // TypeScript Rest Parameter with Default Values 65 | function concatenate(separator: string = ", ", ...strings: string[]): string { 66 | return strings.join(separator); 67 | } 68 | ``` 69 | 70 | 71 | ### Use Cases: 72 | 73 | - **Handling Optional Parameters:** 74 | Default parameters are useful for making function parameters optional without explicitly checking for `undefined` or using conditional logic. 75 | 76 | ```tsx 77 | function printDetails(name: string, age?: number, city: string = "Unknown"): void { 78 | console.log(`Name: ${name}, Age: ${age || "Not specified"}, City: ${city}`); 79 | } 80 | ``` 81 | 82 | - **Providing Default Values:** 83 | When a parameter is not provided, the default value ensures that the function still behaves as expected. 84 | 85 | ```tsx 86 | function greet(name: string = "Guest", greeting: string = "Hello"): void { 87 | console.log(`${greeting}, ${name}!`); 88 | } 89 | ``` 90 | 91 | - **Avoiding `undefined`:** 92 | Default parameters can help avoid issues related to `undefined` values when a parameter is not provided. 93 | 94 | ```tsx 95 | function processData(data: string[] = []): void { 96 | // Process the data array 97 | } 98 | ``` 99 | 100 | 101 | Default function parameters provide a convenient way to make functions more flexible, handle optional parameters, and set default values, improving the readability and maintainability of code. -------------------------------------------------------------------------------- /Next-generation JavaScript & TypeScript/Let & Const.md: -------------------------------------------------------------------------------- 1 | # Let & Const 2 | 3 | The `let` and `const` keywords in JavaScript and TypeScript were introduced as part of ECMAScript 6 (ES6) and represent an enhancement to variable declarations compared to the traditional `var` keyword. Here's an overview of these next-generation variable declaration keywords: 4 | 5 | ### `let`: 6 | 7 | - **Scope:** Variables declared with `let` have block scope, meaning they are confined to the block (enclosed by curly braces) in which they are defined. This is in contrast to `var`, which has function scope. 8 | - **Redeclaration:** Variables declared with `let` cannot be redeclared within the same block scope. This helps avoid unintentional variable shadowing. 9 | - **Hoisting:** Like `var`, `let` is hoisted to the top of its block scope during the compilation phase. However, unlike `var`, the variable is not initialized until the declaration statement is encountered during runtime. 10 | - **Example:** 11 | 12 | ```tsx 13 | function example() { 14 | if (true) { 15 | let x = 10; 16 | console.log(x); // 10 17 | } 18 | console.log(x); // Error: x is not defined 19 | } 20 | ``` 21 | 22 | 23 | ### `const`: 24 | 25 | - **Immutable Binding:** Variables declared with `const` are constants and cannot be reassigned after initialization. The value of a `const` variable remains constant throughout its scope. 26 | - **Block Scope:** Similar to `let`, `const` also has block scope. Once a `const` variable is assigned a value, that value cannot be changed. 27 | - **Declaration and Initialization:** A `const` variable must be both declared and initialized at the same time. Attempting to declare a `const` variable without initialization or reassign its value later results in an error. 28 | - **Example:** 29 | 30 | ```tsx 31 | function example() { 32 | const PI = 3.14; 33 | console.log(PI); // 3.14 34 | 35 | // Error: Cannot assign to 'PI' because it is a constant. 36 | PI = 3.14159; 37 | } 38 | ``` 39 | 40 | 41 | ### Use Cases: 42 | 43 | - **`let`:** Use `let` when you need a variable whose value can be reassigned, and you want to confine its scope to a specific block. 44 | - **`const`:** Use `const` for constants or variables that should not be reassigned. This is helpful for preventing accidental mutation of values. 45 | 46 | ### TypeScript: 47 | 48 | In TypeScript, `let` and `const` work similarly to JavaScript. TypeScript adds static typing to these variables, allowing you to explicitly specify the type or let TypeScript infer the type based on the initialization. 49 | 50 | ```tsx 51 | let message: string = "Hello"; 52 | const PI: number = 3.14; 53 | 54 | message = "World"; // Valid for let 55 | // Error: Cannot assign to 'PI' because it is a constant. 56 | PI = 3.14159; // Invalid for const 57 | ``` 58 | 59 | Using `let` and `const` in TypeScript provides the benefits of improved scoping, prevention of accidental reassignments (for `const`), and static typing for more robust code. -------------------------------------------------------------------------------- /Next-generation JavaScript & TypeScript/README.md: -------------------------------------------------------------------------------- 1 | # Next-generation JavaScript & TypeScript 2 | 3 | ## Introduction 4 | 5 | Welcome to the exploration of next-generation JavaScript and TypeScript! In this comprehensive guide, we delve into modern language features and concepts that empower developers to write more efficient and expressive code. From understanding the nuances of `let` and `const` declarations to harnessing the power of arrow functions and leveraging advanced techniques like the spread operator and rest parameters, this resource serves as a valuable reference for mastering the latest advancements in JavaScript and TypeScript development. Join us on this journey as we unravel the intricacies of next-generation language features and elevate your coding skills to new heights. 6 | 7 | ## Table of Contents 8 | 9 | - [Let & Const](./Let%20&%20Const.md) 10 | - [Arrow Functions](./Arrow%20Functions.md) 11 | - [Default Function Parameters](./Default%20Function%20Parameters.md) 12 | - [The Spread Operator (…)](./The%20Spread%20Operator%20(…).md) 13 | - [Rest Parameters](./Rest%20Parameters.md) 14 | - [Array & Object Destructuring](./Array%20&%20Object%20Destructuring.md) -------------------------------------------------------------------------------- /Next-generation JavaScript & TypeScript/Rest Parameters.md: -------------------------------------------------------------------------------- 1 | # Rest Parameters 2 | 3 | Rest parameters, introduced in ECMAScript 6 (ES6) and supported in both JavaScript and TypeScript, allow a function to accept an arbitrary number of arguments as an array. The rest parameter syntax uses the ellipsis (`...`) followed by the parameter name. Rest parameters provide a concise way to handle variable-length argument lists. 4 | 5 | ### Rest Parameters in JavaScript: 6 | 7 | ### 1. **Syntax:** 8 | 9 | ```jsx 10 | function sum(...numbers) { 11 | return numbers.reduce((acc, val) => acc + val, 0); 12 | } 13 | 14 | console.log(sum(1, 2, 3)); // Output: 6 15 | console.log(sum(1, 2, 3, 4, 5)); // Output: 15 16 | ``` 17 | 18 | ### 2. **Rest Parameter and Regular Parameters:** 19 | 20 | The rest parameter must be the last parameter in the function parameter list. 21 | 22 | ```jsx 23 | function example(a, b, ...rest) { 24 | console.log(a); // 1 25 | console.log(b); // 2 26 | console.log(rest); // [3, 4, 5] 27 | } 28 | 29 | example(1, 2, 3, 4, 5); 30 | ``` 31 | 32 | ### Rest Parameters in TypeScript: 33 | 34 | ### 1. **Syntax:** 35 | 36 | In TypeScript, you can explicitly specify the type of the rest parameter as an array. 37 | 38 | ```tsx 39 | function sum(...numbers: number[]): number { 40 | return numbers.reduce((acc, val) => acc + val, 0); 41 | } 42 | ``` 43 | 44 | ### 2. **Rest Parameter with Type Union:** 45 | 46 | Rest parameters can also be combined with other parameters, and TypeScript can infer or enforce specific types. 47 | 48 | ```tsx 49 | function printInfo(name: string, age: number, ...hobbies: string[]): void { 50 | console.log(`Name: ${name}, Age: ${age}`); 51 | console.log(`Hobbies: ${hobbies.join(', ')}`); 52 | } 53 | ``` 54 | 55 | ### Use Cases: 56 | 57 | - **Variable-Length Argument Lists:** 58 | Rest parameters are useful when a function needs to handle an arbitrary number of arguments. 59 | 60 | ```tsx 61 | function average(...numbers: number[]): number { 62 | const sum = numbers.reduce((acc, val) => acc + val, 0); 63 | return sum / numbers.length; 64 | } 65 | ``` 66 | 67 | - **Combining Rest Parameter with Other Parameters:** 68 | Rest parameters can be combined with regular parameters, allowing for flexibility in function signatures. 69 | 70 | ```tsx 71 | function printInfo(name: string, age: number, ...hobbies: string[]): void { 72 | console.log(`Name: ${name}, Age: ${age}`); 73 | console.log(`Hobbies: ${hobbies.join(', ')}`); 74 | } 75 | ``` 76 | 77 | - **Array Destructuring:** 78 | Rest parameters work well with array destructuring, allowing you to extract specific values. 79 | 80 | ```tsx 81 | function processArray(...elements: number[]): void { 82 | const [first, second, ...remaining] = elements; 83 | // Process individual elements or the remaining array 84 | } 85 | ``` 86 | 87 | 88 | Rest parameters offer a convenient way to handle functions with varying numbers of arguments, promoting flexibility and cleaner function signatures. They are particularly useful in scenarios where the exact number of arguments is not known in advance. -------------------------------------------------------------------------------- /Next-generation JavaScript & TypeScript/The Spread Operator (…).md: -------------------------------------------------------------------------------- 1 | # The Spread Operator (…) 2 | 3 | The spread operator (`...`) in both JavaScript and TypeScript is a powerful feature introduced in ECMAScript 6 (ES6). It is used to spread or unpack the elements of an iterable (like an array or a string) into individual elements. The spread operator is versatile and can be employed in various scenarios. 4 | 5 | ### Spread Operator in JavaScript: 6 | 7 | ### 1. **Spreading Array Elements:** 8 | 9 | ```jsx 10 | const numbers = [1, 2, 3]; 11 | const newArray = [...numbers, 4, 5, 6]; 12 | console.log(newArray); // Output: [1, 2, 3, 4, 5, 6] 13 | ``` 14 | 15 | ### 2. **Copying Arrays:** 16 | 17 | The spread operator can be used to create a shallow copy of an array. 18 | 19 | ```jsx 20 | const originalArray = [1, 2, 3]; 21 | const copyArray = [...originalArray]; 22 | ``` 23 | 24 | ### 3. **Spreading String Characters:** 25 | 26 | ```jsx 27 | const str = "hello"; 28 | const charArray = [...str]; 29 | console.log(charArray); // Output: ['h', 'e', 'l', 'l', 'o'] 30 | ``` 31 | 32 | ### 4. **Merging Objects:** 33 | 34 | The spread operator can be used to merge objects (shallow merge). 35 | 36 | ```jsx 37 | const obj1 = { a: 1, b: 2 }; 38 | const obj2 = { c: 3, d: 4 }; 39 | const mergedObject = { ...obj1, ...obj2 }; 40 | 41 | ``` 42 | 43 | ### Spread Operator in TypeScript: 44 | 45 | In TypeScript, the spread operator can be used similarly to JavaScript, and it integrates well with TypeScript's type system. 46 | 47 | ### 1. **Spreading Arrays:** 48 | 49 | ```tsx 50 | const numbers: number[] = [1, 2, 3]; 51 | const newArray: number[] = [...numbers, 4, 5, 6]; 52 | ``` 53 | 54 | ### 2. **Copying Arrays with Types:** 55 | 56 | In TypeScript, you can also spread tuples and other array-like structures. 57 | 58 | ```tsx 59 | const originalArray: [string, number] = ['hello', 42]; 60 | const copyArray: [string, number] = [...originalArray]; 61 | ``` 62 | 63 | ### 3. **Spreading Objects:** 64 | 65 | ```tsx 66 | const obj1: { a: number, b: number } = { a: 1, b: 2 }; 67 | const obj2: { c: number, d: number } = { c: 3, d: 4 }; 68 | const mergedObject: { a: number, b: number, c: number, d: number } = { ...obj1, ...obj2 }; 69 | ``` 70 | 71 | ### 4. **Immutability:** 72 | 73 | The spread operator is often used in an immutable fashion, creating new objects or arrays instead of modifying existing ones. 74 | 75 | ```tsx 76 | const originalArray: number[] = [1, 2, 3]; 77 | const modifiedArray: number[] = [...originalArray, 4, 5, 6]; 78 | ``` 79 | 80 | ### Use Cases: 81 | 82 | - **Immutability:** 83 | Use the spread operator to create new arrays or objects with additional elements without modifying the original ones. 84 | - **Function Arguments:** 85 | Pass an array or iterable of values as separate arguments to a function. 86 | 87 | ```tsx 88 | function sum(...numbers: number[]): number { 89 | return numbers.reduce((acc, val) => acc + val, 0); 90 | } 91 | ``` 92 | 93 | - **Object Merging:** 94 | Use the spread operator for merging objects while maintaining immutability. 95 | 96 | ```tsx 97 | const obj1 = { a: 1, b: 2 }; 98 | const obj2 = { c: 3, d: 4 }; 99 | const mergedObject = { ...obj1, ...obj2 }; 100 | ``` 101 | 102 | 103 | The spread operator is a versatile tool that simplifies various tasks related to arrays, strings, and objects. It promotes a more functional and immutable programming style, making code clearer and less error-prone. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TypeScript Cookbook 2 | 3 | ![tscookbookcover](./tscookbookcover.png) 4 | 5 | ## Introduction 6 | 7 | The TypeScript Cookbook is a straightforward and digestible guide to TypeScript. 8 | 9 | ## Table of Contents 10 | 11 | - [Getting Started](./Getting%20Started/README.md) 12 | - [What Is TypeScript & Why Should You Use It?](./Getting%20Started/What%20Is%20TypeScript%20&%20Why%20Should%20You%20Use%20It.md) 13 | - [Installing & Using TypeScript](./Getting%20Started/Installing%20&%20Using%20TypeScript.md) 14 | - [TypeScript Advantages](./Getting%20Started/TypeScript%20Advantages.md) 15 | - [TypeScript Basics & Basic Types](./TypeScript%20Basics%20&%20Basic%20Types/) 16 | - [Using Types](./TypeScript%20Basics%20&%20Basic%20Types/Using%20Types.md) 17 | - [TypeScript Types vs JavaScript Types](./TypeScript%20Basics%20&%20Basic%20Types/TypeScript%20Types%20vs%20JavaScript%20Types.md) 18 | - [Type Casing](./TypeScript%20Basics%20&%20Basic%20Types/Type%20Casing.md) 19 | - [Working with Numbers, Strings & Booleans](./TypeScript%20Basics%20&%20Basic%20Types/Working%20with%20Numbers,%20Strings%20&%20Booleans.md) 20 | - [Type Assignment & Type Inference](./TypeScript%20Basics%20&%20Basic%20Types/Type%20Assignment%20&%20Type%20Inference.md) 21 | - [Understanding Types](./TypeScript%20Basics%20&%20Basic%20Types/Understanding%20Types.md) 22 | - [Object Types](./TypeScript%20Basics%20&%20Basic%20Types/Object%20Types.md) 23 | - [Nested Objects & Types](./TypeScript%20Basics%20&%20Basic%20Types/Nested%20Objects%20&%20Types.md) 24 | - [Arrays Types](./TypeScript%20Basics%20&%20Basic%20Types/Arrays%20Type.md) 25 | - [Working with Tuples](./TypeScript%20Basics%20&%20Basic%20Types/Working%20with%20Tuples.md) 26 | - [Working with Enums](./TypeScript%20Basics%20&%20Basic%20Types/Working%20with%20Enums.md) 27 | - [The "any" Type](./TypeScript%20Basics%20&%20Basic%20Types/The%20any%20Type.md) 28 | - [Union Types](./TypeScript%20Basics%20&%20Basic%20Types/Union%20Types.md) 29 | - [Literal Types](./TypeScript%20Basics%20&%20Basic%20Types/Literal%20Types.md) 30 | - [Type Aliases / Custom Types](./TypeScript%20Basics%20&%20Basic%20Types/Type%20Aliases%20Custom%20Types.md) 31 | - [Type Aliases & Object Types](./TypeScript%20Basics%20&%20Basic%20Types/Type%20Aliases%20&%20Object%20Types.md) 32 | - [Core Types & Concepts](./TypeScript%20Basics%20&%20Basic%20Types/Core%20Types%20&%20Concepts.md) 33 | - [Function Return Types & "void”](./TypeScript%20Basics%20&%20Basic%20Types/Function%20Return%20Types%20&%20void”.md) 34 | - [Functions as Types](./TypeScript%20Basics%20&%20Basic%20Types/Functions%20as%20Types.md) 35 | - [Function Types & Callbacks](/TypeScript%20Basics%20&%20Basic%20Types/Function%20Types%20&%20Callbacks.md) 36 | - [Functions & Types](./TypeScript%20Basics%20&%20Basic%20Types/Functions%20&%20Types.md) 37 | - [The "unknown" Type](./TypeScript%20Basics%20&%20Basic%20Types/The%20unknown%20Type.md) 38 | - [The "never" Type](./TypeScript%20Basics%20&%20Basic%20Types/The%20never%20Type.md) 39 | - [TypeScript Compiler](./TypeScript%20Compiler/) 40 | - [Introduction](./TypeScript%20Compiler/Introduction.md) 41 | - [Compiling the Entire Project / Multiple Files](./TypeScript%20Compiler/Compiling%20the%20Entire%20Project%20Multiple%20Files.md) 42 | - [Including & Excluding Files](./TypeScript%20Compiler/Including%20&%20Excluding%20Files.md) 43 | - [Setting a Compilation Target](./TypeScript%20Compiler/Setting%20a%20Compilation%20Target.md) 44 | - [Understanding TypeScript Core Libs](./TypeScript%20Compiler/Understanding%20TypeScript%20Core%20Libs.md) 45 | - [Next-generation JavaScript & TypeScript](./Next-generation%20JavaScript%20&%20TypeScript/) 46 | - [Let & Const](./Next-generation%20JavaScript%20&%20TypeScript/Let%20&%20Const.md) 47 | - [Arrow Functions](./Next-generation%20JavaScript%20&%20TypeScript/Arrow%20Functions.md) 48 | - [Default Function Parameters](./Next-generation%20JavaScript%20&%20TypeScript/Default%20Function%20Parameters.md) 49 | - [The Spread Operator (…)](./Next-generation%20JavaScript%20&%20TypeScript/The%20Spread%20Operator%20(…).md) 50 | - [Rest Parameters](./Next-generation%20JavaScript%20&%20TypeScript/Rest%20Parameters.md) 51 | - [Array & Object Destructuring](./Next-generation%20JavaScript%20&%20TypeScript/Array%20&%20Object%20Destructuring.md) 52 | - [Classes & Interfaces](./Classes%20&%20Interfaces/) 53 | - [What are Classes?](./Classes%20&%20Interfaces/What%20are%20Classes.md) 54 | - [Constructor Functions & The "this" Keyword](./Classes%20&%20Interfaces/Constructor%20Functions%20&%20The%20this%20Keyword.md) 55 | - ["Private" and "Public" Access Modifiers](./Classes%20&%20Interfaces/Private%20and%20Public%20Access%20Modifiers.md) 56 | - ["Readonly" Properties](./Classes%20&%20Interfaces/Readonly%20Properties.md) 57 | - [Inheritance](./Classes%20&%20Interfaces/Inheritance.md) 58 | - [Overriding Properties & The "protected" Modifier](./Classes%20&%20Interfaces/Overriding%20Properties%20&%20The%20protected%20Modifier.md) 59 | - [Getters & Setters](./Classes%20&%20Interfaces/Getters%20&%20Setters.md) -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Arrays Type.md: -------------------------------------------------------------------------------- 1 | # Arrays Types 2 | 3 | ## Introduction 4 | 5 | You can define types for arrays to specify the types of elements they contain. Here are several ways to work with array types: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Basic Array Types:**](#1-basic-array-types) 10 | - [2. **Array Type with Union:**](#2-array-type-with-union) 11 | - [3. **Array Type with Generics:**](#3-array-type-with-generics) 12 | - [4. **Tuple Types:**](#4-tuple-types) 13 | - [5. **Array of Objects:**](#5-array-of-objects) 14 | - [6. **Readonly Arrays:**](#6-readonly-arrays) 15 | - [7. **Array Type Assertion:**](#7-array-type-assertion) 16 | - [8. **Array Type Inference:**](#8-array-type-inference) 17 | - [9. **Rest Parameters and Spread Operator:**](#9-rest-parameters-and-spread-operator) 18 | - [10. **Array Methods with Type Inference:**](#10-array-methods-with-type-inference) 19 | 20 | ### 1. **Basic Array Types:** 21 | 22 | ```tsx 23 | // Array of numbers 24 | let numbers: number[] = [1, 2, 3, 4, 5]; 25 | 26 | // Array of strings 27 | let names: string[] = ["John", "Alice", "Bob"]; 28 | 29 | // Array of booleans 30 | let flags: boolean[] = [true, false, true]; 31 | ``` 32 | 33 | ### 2. **Array Type with Union:** 34 | 35 | ```tsx 36 | // Array of numbers or strings 37 | let mixedArray: (number | string)[] = [1, "two", 3, "four"]; 38 | ``` 39 | 40 | ### 3. **Array Type with Generics:** 41 | 42 | ```tsx 43 | // Generic array type 44 | let genericArray: Array = [1, 2, 3]; 45 | ``` 46 | 47 | ### 4. **Tuple Types:** 48 | 49 | Tuples allow you to specify the type of each element at a specific position in the array. 50 | 51 | ```tsx 52 | // Tuple with specified types 53 | let tuple: [string, number, boolean] = ["John", 30, true]; 54 | ``` 55 | 56 | ### 5. **Array of Objects:** 57 | 58 | ```tsx 59 | // Array of objects with a specific shape 60 | type Person = { name: string; age: number }; 61 | let people: Person[] = [ 62 | { name: "John", age: 30 }, 63 | { name: "Alice", age: 25 }, 64 | ]; 65 | ``` 66 | 67 | ### 6. **Readonly Arrays:** 68 | 69 | ```tsx 70 | // Readonly array 71 | let readonlyArray: ReadonlyArray = [1, 2, 3]; 72 | // readonlyArray[0] = 4; // Error: Index signature in type 'readonly number[]' only permits reading. 73 | ``` 74 | 75 | ### 7. **Array Type Assertion:** 76 | 77 | ```tsx 78 | // Array type assertion 79 | let anyArray: any[] = [1, "two", true]; 80 | let stringArray: string[] = anyArray as string[]; 81 | ``` 82 | 83 | ### 8. **Array Type Inference:** 84 | 85 | ```tsx 86 | // TypeScript infers the array type 87 | let inferredArray = [1, 2, 3]; // inferredArray is of type number[] 88 | ``` 89 | 90 | ### 9. **Rest Parameters and Spread Operator:** 91 | 92 | ```tsx 93 | // Rest parameters in function 94 | function mergeArrays(...arrays: number[][]): number[] { 95 | return [].concat(...arrays); 96 | } 97 | 98 | let merged: number[] = mergeArrays([1, 2], [3, 4], [5, 6]); 99 | ``` 100 | 101 | ### 10. **Array Methods with Type Inference:** 102 | 103 | ```tsx 104 | // Array methods with type inference 105 | let numbers = [1, 2, 3]; 106 | let doubledNumbers = numbers.map((num) => num * 2); // doubledNumbers is inferred as number[] 107 | ``` 108 | 109 | These examples illustrate different ways to define and use array types in TypeScript. Choose the approach that best fits your use case, and leverage TypeScript's static typing to catch potential errors early in the development process. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Core Types & Concepts.md: -------------------------------------------------------------------------------- 1 | # Core Types & Concepts 2 | 3 | ## Introduction 4 | 5 | There are several core types and concepts that form the foundation of the language. Here's an overview of some key TypeScript concepts and common core types: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Basic Types:**](#1-basic-types) 10 | - [a. **`number`:**](#a-number) 11 | - [b. **`string`:**](#b-string) 12 | - [c. **`boolean`:**](#c-boolean) 13 | - [d. **`null` and `undefined`:**](#d-null-and-undefined) 14 | - [e. **`any`:**](#e-any) 15 | - [2. **Type Annotations:**](#2-type-annotations) 16 | - [3. **Interfaces:**](#3-interfaces) 17 | - [4. **Arrays:**](#4-arrays) 18 | - [5. **Functions:**](#5-functions) 19 | - [6. **Union Types:**](#6-union-types) 20 | - [7. **Literal Types:**](#7-literal-types) 21 | - [8. **Enums:**](#8-enums) 22 | - [9. **Type Aliases:**](#9-type-aliases) 23 | - [10. **Generics:**](#10-generics) 24 | 25 | ### 1. **Basic Types:** 26 | 27 | ### a. **`number`:** 28 | 29 | Represents both integer and floating-point numbers. 30 | 31 | ```tsx 32 | let count: number = 42; 33 | ``` 34 | 35 | ### b. **`string`:** 36 | 37 | Represents textual data. 38 | 39 | ```tsx 40 | let message: string = "Hello, TypeScript!"; 41 | ``` 42 | 43 | ### c. **`boolean`:** 44 | 45 | Represents a binary choice, `true` or `false`. 46 | 47 | ```tsx 48 | let isDone: boolean = false; 49 | 50 | ``` 51 | 52 | ### d. **`null` and `undefined`:** 53 | 54 | Represent absence of value. 55 | 56 | ```tsx 57 | let data: null = null; 58 | let value: undefined = undefined; 59 | ``` 60 | 61 | ### e. **`any`:** 62 | 63 | Represents a dynamic or unknown type, opting out of static type checking. 64 | 65 | ```tsx 66 | let dynamicValue: any = 42; 67 | ``` 68 | 69 | ### 2. **Type Annotations:** 70 | 71 | Type annotations allow you to explicitly specify the type of a variable or function parameter. 72 | 73 | ```tsx 74 | let age: number = 25; 75 | 76 | function greet(name: string): string { 77 | return `Hello, ${name}!`; 78 | } 79 | ``` 80 | 81 | ### 3. **Interfaces:** 82 | 83 | Interfaces define contracts for object shapes. They can include properties, methods, and optional members. 84 | 85 | ```tsx 86 | interface Person { 87 | name: string; 88 | age: number; 89 | } 90 | 91 | let john: Person = { name: "John", age: 30 }; 92 | ``` 93 | 94 | ### 4. **Arrays:** 95 | 96 | Arrays in TypeScript can be of a specific type or a union of types. 97 | 98 | ```tsx 99 | let numbers: number[] = [1, 2, 3]; 100 | let mixedArray: (number | string)[] = [1, "two", 3]; 101 | ``` 102 | 103 | ### 5. **Functions:** 104 | 105 | Functions can have parameter types and return types. 106 | 107 | ```tsx 108 | function add(a: number, b: number): number { 109 | return a + b; 110 | } 111 | ``` 112 | 113 | ### 6. **Union Types:** 114 | 115 | Union types allow a variable to have one of several types. 116 | 117 | ```tsx 118 | let result: number | string = 42; 119 | result = "Success"; 120 | ``` 121 | 122 | ### 7. **Literal Types:** 123 | 124 | Literal types allow you to specify exact values as types. 125 | 126 | ```tsx 127 | let status: "success" | "failure" = "success"; 128 | ``` 129 | 130 | ### 8. **Enums:** 131 | 132 | Enums allow you to define named constant values representing discrete elements or categories. 133 | 134 | ```tsx 135 | enum Color { 136 | Red, 137 | Green, 138 | Blue, 139 | } 140 | 141 | let myColor: Color = Color.Green; 142 | ``` 143 | 144 | ### 9. **Type Aliases:** 145 | 146 | Type aliases provide a way to create custom names for types, improving code readability. 147 | 148 | ```tsx 149 | type Point = { 150 | x: number; 151 | y: number; 152 | }; 153 | 154 | let position: Point = { x: 5, y: 10 }; 155 | ``` 156 | 157 | ### 10. **Generics:** 158 | 159 | Generics enable the creation of reusable and flexible components with type parameters. 160 | 161 | ```tsx 162 | function identity(arg: T): T { 163 | return arg; 164 | } 165 | 166 | let result: string = identity("Hello, TypeScript!"); 167 | ``` 168 | 169 | These core types and concepts form the basis of TypeScript's static typing system, providing tools to express the structure and behavior of your code. Understanding and leveraging these concepts is crucial for writing robust and maintainable TypeScript code. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Function Return Types & void”.md: -------------------------------------------------------------------------------- 1 | # Function Return Types & "void” 2 | 3 | ## Introduction 4 | 5 | Function return types specify the type of the value that a function will return. The `void` type is used when a function does not return any value. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Specifying Function Return Types:**](#1-specifying-function-return-types) 10 | - [2. **Void Return Type:**](#2-void-return-type) 11 | - [3. **Functions with No Return Type:**](#3-functions-with-no-return-type) 12 | - [4. **Using "undefined" Return Type:**](#4-using-undefined-return-type) 13 | - [5. **Never Return Type:**](#5-never-return-type) 14 | - [6. **Function Type Declarations:**](#6-function-type-declarations) 15 | 16 | ### 1. **Specifying Function Return Types:** 17 | 18 | You can explicitly specify the return type of a function using the `: returnType` syntax. 19 | 20 | ```tsx 21 | function add(a: number, b: number): number { 22 | return a + b; 23 | } 24 | ``` 25 | 26 | In this example, the function `add` takes two parameters of type `number` and returns a value of type `number`. 27 | 28 | ### 2. **Void Return Type:** 29 | 30 | The `void` type is used when a function does not return any value. It indicates that the function performs an action but does not produce a result. 31 | 32 | ```tsx 33 | function logMessage(message: string): void { 34 | console.log(message); 35 | } 36 | ``` 37 | 38 | Here, `logMessage` logs a message to the console but does not return a value. 39 | 40 | ### 3. **Functions with No Return Type:** 41 | 42 | When a function does not have a `return` statement or the `return` statement has no expression, TypeScript infers the return type as `void`. 43 | 44 | ```tsx 45 | function greet(name: string): void { 46 | console.log(`Hello, ${name}!`); 47 | } 48 | 49 | function throwError(message: string): never { 50 | throw new Error(message); 51 | } 52 | ``` 53 | 54 | In the `greet` function, TypeScript infers `void` because there is no explicit return type and no `return` statement with an expression. 55 | 56 | ### 4. **Using "undefined" Return Type:** 57 | 58 | You can also use the `undefined` type as a return type to indicate that the function returns a value of `undefined`. 59 | 60 | ```tsx 61 | function getOption(option: string): string | undefined { 62 | if (option === "enabled") { 63 | return "The option is enabled."; 64 | } else { 65 | return undefined; 66 | } 67 | } 68 | ``` 69 | 70 | In this example, the function `getOption` returns either a string or `undefined`. 71 | 72 | ### 5. **Never Return Type:** 73 | 74 | The `never` type is used when a function never produces a value or always throws an exception. 75 | 76 | ```tsx 77 | function throwError(message: string): never { 78 | throw new Error(message); 79 | } 80 | ``` 81 | 82 | Here, the `throwError` function has a `never` return type because it always throws an exception. 83 | 84 | ### 6. **Function Type Declarations:** 85 | 86 | When using function type declarations, you can also specify the return type. 87 | 88 | ```tsx 89 | type MathOperation = (a: number, b: number) => number; 90 | 91 | const add: MathOperation = (a, b) => a + b; 92 | const subtract: MathOperation = (a, b) => a - b; 93 | ``` 94 | 95 | In this example, the `MathOperation` type defines functions that take two parameters of type `number` and return a value of type `number`. 96 | 97 | Understanding function return types and using them appropriately enhances the clarity and maintainability of your TypeScript code, as it helps TypeScript catch potential errors during development. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Function Types & Callbacks.md: -------------------------------------------------------------------------------- 1 | # Function Types & Callbacks 2 | 3 | ## Introduction 4 | 5 | Function types and callbacks are integral concepts that enhance the flexibility and type safety of your code. Let's explore how function types and callbacks work in TypeScript. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Function Types:**](#1-function-types) 10 | - [2. **Callbacks:**](#2-callbacks) 11 | - [3. **Function Types with Callbacks:**](#3-function-types-with-callbacks) 12 | 13 | ### 1. **Function Types:** 14 | 15 | Function types define the shape of a function, including the types of its parameters and the type of its return value. Here's an example: 16 | 17 | ```tsx 18 | type MathOperation = (a: number, b: number) => number; 19 | 20 | const add: MathOperation = (a, b) => a + b; 21 | const subtract: MathOperation = (a, b) => a - b; 22 | ``` 23 | 24 | In this example, `MathOperation` is a function type representing a function that takes two `number` parameters and returns a `number`. The `add` and `subtract` functions conform to this type. 25 | 26 | ### 2. **Callbacks:** 27 | 28 | Callbacks are functions passed as arguments to other functions. They are commonly used in asynchronous operations and event handling. Here's an example of a callback in TypeScript: 29 | 30 | ```tsx 31 | type CallbackFunction = (result: number) => void; 32 | 33 | function performOperation(a: number, b: number, callback: CallbackFunction): void { 34 | const result = a + b; 35 | callback(result); 36 | } 37 | 38 | // Using the performOperation function with a callback 39 | const printResult: CallbackFunction = (result) => { 40 | console.log(`Result: ${result}`); 41 | }; 42 | 43 | performOperation(3, 7, printResult); 44 | ``` 45 | 46 | In this example, `CallbackFunction` is a type representing a callback function that takes a `number` parameter and returns `void`. The `performOperation` function takes two numbers and a callback function, performs an operation, and invokes the callback with the result. 47 | 48 | ### 3. **Function Types with Callbacks:** 49 | 50 | You can combine function types and callbacks to define clear interfaces for functions that accept callbacks. Here's an example: 51 | 52 | ```tsx 53 | type OperationCallback = (result: number) => void; 54 | type MathOperationWithCallback = (a: number, b: number, callback: OperationCallback) => void; 55 | 56 | const addWithCallback: MathOperationWithCallback = (a, b, callback) => { 57 | const result = a + b; 58 | callback(result); 59 | }; 60 | 61 | // Using the addWithCallback function 62 | addWithCallback(5, 8, (result) => { 63 | console.log(`Sum: ${result}`); 64 | }); 65 | ``` 66 | 67 | In this example, `OperationCallback` is a type representing a callback function, and `MathOperationWithCallback` is a function type representing a math operation that accepts two numbers and a callback. The `addWithCallback` function conforms to this type. 68 | 69 | By utilizing function types and callbacks, TypeScript allows you to express clear and reusable patterns in your code, improving type safety and enhancing the readability of your functions. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Functions & Types.md: -------------------------------------------------------------------------------- 1 | # Functions & Types 2 | 3 | ## Introduction 4 | 5 | Functions are first-class citizens, and you can define types for functions to provide clear interfaces and enforce type safety. Here's an overview of how functions and types are used together in TypeScript: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Function Declarations:**](#1-function-declarations) 10 | - [2. **Function Expressions:**](#2-function-expressions) 11 | - [3. **Function Types:**](#3-function-types) 12 | - [4. **Optional and Default Parameters:**](#4-optional-and-default-parameters) 13 | - [5. **Rest Parameters:**](#5-rest-parameters) 14 | - [6. **Function Types as Parameters:**](#6-function-types-as-parameters) 15 | - [7. **Generic Functions:**](#7-generic-functions) 16 | - [8. **Function Overloads:**](#8-function-overloads) 17 | - [9. **Callbacks:**](#9-callbacks) 18 | 19 | ### 1. **Function Declarations:** 20 | 21 | You can declare functions with type annotations for parameters and return types: 22 | 23 | ```tsx 24 | function add(a: number, b: number): number { 25 | return a + b; 26 | } 27 | ``` 28 | 29 | In this example, the `add` function takes two parameters (`a` and `b`) of type `number` and returns a value of type `number`. 30 | 31 | ### 2. **Function Expressions:** 32 | 33 | Functions can also be assigned to variables and used as expressions: 34 | 35 | ```tsx 36 | const subtract: (a: number, b: number) => number = function (a, b) { 37 | return a - b; 38 | }; 39 | ``` 40 | 41 | Here, the `subtract` variable is assigned a function expression with a specified type for parameters and return value. 42 | 43 | ### 3. **Function Types:** 44 | 45 | You can define function types separately using the `type` keyword: 46 | 47 | ```tsx 48 | type MathOperation = (a: number, b: number) => number; 49 | ``` 50 | 51 | Now, you can use this type to declare functions or variables: 52 | 53 | ```tsx 54 | const multiply: MathOperation = (a, b) => a * b; 55 | ``` 56 | 57 | ### 4. **Optional and Default Parameters:** 58 | 59 | Function types can include optional and default parameters: 60 | 61 | ```tsx 62 | type PrintMessageFunction = (message: string, urgency?: boolean) => void; 63 | 64 | const printMessage: PrintMessageFunction = (message, urgency = false) => { 65 | console.log(urgency ? `URGENT: ${message}` : message); 66 | }; 67 | ``` 68 | 69 | ### 5. **Rest Parameters:** 70 | 71 | Function types can also include rest parameters: 72 | 73 | ```tsx 74 | type SumFunction = (...numbers: number[]) => number; 75 | 76 | const sum: SumFunction = (...numbers) => numbers.reduce((acc, num) => acc + num, 0); 77 | ``` 78 | 79 | ### 6. **Function Types as Parameters:** 80 | 81 | You can use function types as parameters: 82 | 83 | ```tsx 84 | type OperationFunction = (a: number, b: number) => number; 85 | 86 | function performOperation(operation: OperationFunction, a: number, b: number): number { 87 | return operation(a, b); 88 | } 89 | ``` 90 | 91 | ### 7. **Generic Functions:** 92 | 93 | You can create generic functions that work with different types: 94 | 95 | ```tsx 96 | function identity(value: T): T { 97 | return value; 98 | } 99 | ``` 100 | 101 | Here, `T` is a generic type parameter. 102 | 103 | ### 8. **Function Overloads:** 104 | 105 | You can use function overloads to specify multiple signatures for a function: 106 | 107 | ```tsx 108 | function greet(name: string): string; 109 | function greet(name: string, age: number): string; 110 | 111 | function greet(name: string, age?: number): string { 112 | if (age !== undefined) { 113 | return `Hello, ${name}! You are ${age} years old.`; 114 | } else { 115 | return `Hello, ${name}!`; 116 | } 117 | } 118 | ``` 119 | 120 | ### 9. **Callbacks:** 121 | 122 | Function types are commonly used with callbacks: 123 | 124 | ```tsx 125 | type CallbackFunction = (result: number) => void; 126 | 127 | function performOperation(a: number, b: number, callback: CallbackFunction): void { 128 | const result = a + b; 129 | callback(result); 130 | } 131 | ``` 132 | 133 | By using function types and types for function parameters, TypeScript helps catch errors during development and provides clear interfaces for functions, contributing to code safety and readability. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Functions as Types.md: -------------------------------------------------------------------------------- 1 | # Functions as Types 2 | 3 | ## Introduction 4 | 5 | Functions can be treated as types, allowing you to define and use function types in a similar way to other types. This concept is known as "Functions as Types" or "Function Types." Here's how you can work with function types in TypeScript: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Function Type Declarations:**](#1-function-type-declarations) 10 | - [2. **Function Interfaces:**](#2-function-interfaces) 11 | - [3. **Type Aliases for Functions:**](#3-type-aliases-for-functions) 12 | - [4. **Optional and Default Parameters:**](#4-optional-and-default-parameters) 13 | - [5. **Rest Parameters:**](#5-rest-parameters) 14 | - [6. **Function Types in Generics:**](#6-function-types-in-generics) 15 | 16 | ### 1. **Function Type Declarations:** 17 | 18 | You can declare a function type using the `type` keyword or `interface` keyword. 19 | 20 | ```tsx 21 | type MathOperation = (a: number, b: number) => number; 22 | 23 | const add: MathOperation = (a, b) => a + b; 24 | const subtract: MathOperation = (a, b) => a - b; 25 | ``` 26 | 27 | In this example, the `MathOperation` type represents a function that takes two parameters of type `number` and returns a value of type `number`. The `add` and `subtract` functions are assigned to this type. 28 | 29 | ### 2. **Function Interfaces:** 30 | 31 | You can use the `interface` keyword to define function types as well. 32 | 33 | ```tsx 34 | interface MathOperation { 35 | (a: number, b: number): number; 36 | } 37 | 38 | const multiply: MathOperation = (a, b) => a * b; 39 | const divide: MathOperation = (a, b) => a / b; 40 | ``` 41 | 42 | The `MathOperation` interface is essentially a function type, and the `multiply` and `divide` functions conform to this interface. 43 | 44 | ### 3. **Type Aliases for Functions:** 45 | 46 | You can also use type aliases for function types. 47 | 48 | ```tsx 49 | type GreetingFunction = (name: string) => void; 50 | 51 | const greet: GreetingFunction = (name) => console.log(`Hello, ${name}!`); 52 | ``` 53 | 54 | Here, `GreetingFunction` is a type alias for a function that takes a `string` parameter and returns `void`. 55 | 56 | ### 4. **Optional and Default Parameters:** 57 | 58 | Function types can also include optional and default parameters. 59 | 60 | ```tsx 61 | type PrintMessageFunction = (message: string, urgency?: boolean) => void; 62 | 63 | const printMessage: PrintMessageFunction = (message, urgency = false) => { 64 | console.log(urgency ? `URGENT: ${message}` : message); 65 | }; 66 | ``` 67 | 68 | ### 5. **Rest Parameters:** 69 | 70 | Function types can include rest parameters. 71 | 72 | ```tsx 73 | type SumFunction = (...numbers: number[]) => number; 74 | 75 | const sum: SumFunction = (...numbers) => numbers.reduce((acc, num) => acc + num, 0); 76 | ``` 77 | 78 | Here, `SumFunction` represents a function that takes any number of parameters and returns a number. 79 | 80 | ### 6. **Function Types in Generics:** 81 | 82 | Function types can be used in generics to create flexible and reusable components. 83 | 84 | ```tsx 85 | type TransformFunction = (input: T) => T; 86 | 87 | function applyTransformation(value: T, transform: TransformFunction): T { 88 | return transform(value); 89 | } 90 | 91 | const addOne: TransformFunction = (num) => num + 1; 92 | const capitalize: TransformFunction = (str) => str.toUpperCase(); 93 | 94 | const result1 = applyTransformation(5, addOne); // Result: 6 95 | const result2 = applyTransformation("hello", capitalize); // Result: "HELLO" 96 | ``` 97 | 98 | In this example, `TransformFunction` is a generic function type that can be applied to different types. 99 | 100 | Using functions as types allows you to define clear and reusable interfaces for your functions, promoting code readability and maintainability in TypeScript. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Literal Types.md: -------------------------------------------------------------------------------- 1 | # Literal Types 2 | 3 | ## Introduction 4 | 5 | Literal types allow you to specify exact values that a variable can have. Literal types are specific values, such as strings, numbers, or booleans, and they are denoted by the actual value itself. This allows for more precise type definitions in certain scenarios. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **String Literal Types:**](#1-string-literal-types) 10 | - [2. **Numeric Literal Types:**](#2-numeric-literal-types) 11 | - [3. **Boolean Literal Types:**](#3-boolean-literal-types) 12 | - [4. **Literal Types in Function Parameters:**](#4-literal-types-in-function-parameters) 13 | - [5. **Literal Types with Type Aliases:**](#5-literal-types-with-type-aliases) 14 | - [6. **Combining Literal Types:**](#6-combining-literal-types) 15 | - [7. **Discriminated Unions:**](#7-discriminated-unions) 16 | 17 | ### 1. **String Literal Types:** 18 | 19 | ```tsx 20 | // Variable with a string literal type 21 | let color: "red" | "green" | "blue"; 22 | color = "red"; // OK 23 | color = "green"; // OK 24 | // color = "yellow"; // Error: Type '"yellow"' is not assignable to type '"red" | "green" | "blue"'. 25 | ``` 26 | 27 | ### 2. **Numeric Literal Types:** 28 | 29 | ```tsx 30 | // Variable with a numeric literal type 31 | let statusCode: 200 | 404 | 500; 32 | statusCode = 200; // OK 33 | // statusCode = 300; // Error: Type '300' is not assignable to type '200 | 404 | 500'. 34 | ``` 35 | 36 | ### 3. **Boolean Literal Types:** 37 | 38 | ```tsx 39 | // Variable with a boolean literal type 40 | let isTrue: true; 41 | isTrue = true; // OK 42 | // isTrue = false; // Error: Type 'false' is not assignable to type 'true'. 43 | ``` 44 | 45 | ### 4. **Literal Types in Function Parameters:** 46 | 47 | ```tsx 48 | // Function with string literal type parameter 49 | function setColor(newColor: "red" | "green" | "blue"): void { 50 | // Implementation... 51 | } 52 | 53 | setColor("red"); // OK 54 | // setColor("yellow"); // Error: Argument of type '"yellow"' is not assignable to parameter of type '"red" | "green" | "blue"'. 55 | ``` 56 | 57 | ### 5. **Literal Types with Type Aliases:** 58 | 59 | ```tsx 60 | // Type alias with string literal types 61 | type Direction = "up" | "down" | "left" | "right"; 62 | 63 | let direction: Direction = "up"; // OK 64 | // direction = "diagonal"; // Error: Type '"diagonal"' is not assignable to type 'Direction'. 65 | ``` 66 | 67 | ### 6. **Combining Literal Types:** 68 | 69 | ```tsx 70 | // Union of string and numeric literal types 71 | let literalUnion: "one" | "two" | 1 | 2; 72 | literalUnion = "two"; // OK 73 | literalUnion = 1; // OK 74 | // literalUnion = 3; // Error: Type '3' is not assignable to type '"one" | "two" | 1 | 2'. 75 | ``` 76 | 77 | ### 7. **Discriminated Unions:** 78 | 79 | Literal types are often used in discriminated unions to create exhaustive checks. 80 | 81 | ```tsx 82 | interface Circle { 83 | kind: "circle"; 84 | radius: number; 85 | } 86 | 87 | interface Square { 88 | kind: "square"; 89 | sideLength: number; 90 | } 91 | 92 | type Shape = Circle | Square; 93 | 94 | function getArea(shape: Shape): number { 95 | switch (shape.kind) { 96 | case "circle": 97 | return Math.PI * Math.pow(shape.radius, 2); 98 | case "square": 99 | return Math.pow(shape.sideLength, 2); 100 | default: 101 | return 0; 102 | } 103 | } 104 | ``` 105 | 106 | Literal types provide a way to express specific values as types, and they are particularly useful when you want to narrow down the possible values a variable can have. They contribute to TypeScript's static type checking by making the types more precise and preventing unintended values. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Nested Objects & Types.md: -------------------------------------------------------------------------------- 1 | # Nested Objects & Types 2 | 3 | ## Introduction 4 | 5 | You can define types for nested objects to represent complex data structures. Let's explore how to define nested objects and types for them: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Simple Nested Object:**](#1-simple-nested-object) 10 | - [2. **Optional Properties in Nested Objects:**](#2-optional-properties-in-nested-objects) 11 | - [3. **Nested Arrays:**](#3-nested-arrays) 12 | - [4. **Recursive Types:**](#4-recursive-types) 13 | - [5. **Union Types for Nested Objects:**](#5-union-types-for-nested-objects) 14 | - [6. **Mapped Types for Nested Objects:**](#6-mapped-types-for-nested-objects) 15 | 16 | ### 1. **Simple Nested Object:** 17 | 18 | ```tsx 19 | type Address = { 20 | street: string; 21 | city: string; 22 | zipCode: string; 23 | }; 24 | 25 | type Person = { 26 | name: string; 27 | age: number; 28 | address: Address; 29 | }; 30 | 31 | const john: Person = { 32 | name: "John", 33 | age: 30, 34 | address: { 35 | street: "123 Main St", 36 | city: "Anytown", 37 | zipCode: "12345", 38 | }, 39 | }; 40 | ``` 41 | 42 | ### 2. **Optional Properties in Nested Objects:** 43 | 44 | ```tsx 45 | type OptionalAddress = { 46 | street?: string; 47 | city?: string; 48 | zipCode?: string; 49 | }; 50 | 51 | type OptionalPerson = { 52 | name: string; 53 | age: number; 54 | address?: OptionalAddress; 55 | }; 56 | 57 | const alice: OptionalPerson = { 58 | name: "Alice", 59 | age: 25, 60 | // address is optional 61 | }; 62 | 63 | ``` 64 | 65 | ### 3. **Nested Arrays:** 66 | 67 | ```tsx 68 | type OrderItem = { 69 | productName: string; 70 | quantity: number; 71 | }; 72 | 73 | type Order = { 74 | orderId: string; 75 | items: OrderItem[]; 76 | }; 77 | 78 | const myOrder: Order = { 79 | orderId: "123456", 80 | items: [ 81 | { productName: "Laptop", quantity: 2 }, 82 | { productName: "Mouse", quantity: 1 }, 83 | ], 84 | }; 85 | ``` 86 | 87 | ### 4. **Recursive Types:** 88 | 89 | You can create recursive types for nested structures that reference themselves. 90 | 91 | ```tsx 92 | type TreeNode = { 93 | value: T; 94 | children?: TreeNode[]; 95 | }; 96 | 97 | const tree: TreeNode = { 98 | value: 1, 99 | children: [ 100 | { 101 | value: 2, 102 | children: [ 103 | { value: 4 }, 104 | { value: 5 }, 105 | ], 106 | }, 107 | { 108 | value: 3, 109 | children: [ 110 | { value: 6 }, 111 | { value: 7 }, 112 | ], 113 | }, 114 | ], 115 | }; 116 | ``` 117 | 118 | ### 5. **Union Types for Nested Objects:** 119 | 120 | ```tsx 121 | type Circle = { kind: "circle"; radius: number }; 122 | type Square = { kind: "square"; sideLength: number }; 123 | type Shape = Circle | Square; 124 | 125 | const circle: Shape = { kind: "circle", radius: 5 }; 126 | const square: Shape = { kind: "square", sideLength: 4 }; 127 | ``` 128 | 129 | ### 6. **Mapped Types for Nested Objects:** 130 | 131 | ```tsx 132 | type Flatten = { 133 | [K in keyof T]: T[K] extends object ? Flatten : T[K]; 134 | }; 135 | 136 | type NestedObject = { 137 | prop1: { 138 | prop2: { 139 | prop3: number; 140 | }; 141 | prop4: string; 142 | }; 143 | prop5: boolean; 144 | }; 145 | 146 | type FlatObject = Flatten; 147 | // Result: { prop1_prop2_prop3: number; prop1_prop4: string; prop5: boolean; } 148 | ``` 149 | 150 | These examples showcase different ways to represent and work with nested objects and types in TypeScript. Choose the approach that best fits the structure and requirements of your data. Using types effectively ensures type safety and helps catch potential errors during development. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Object Types.md: -------------------------------------------------------------------------------- 1 | # Object Types 2 | 3 | ## Introduction 4 | 5 | Object types allow you to define the shape of objects by specifying the types of their properties. There are several ways to define object types, and we'll explore the most common approaches: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Object Literal:**](#1-object-literal) 10 | - [2. **Interface:**](#2-interface) 11 | - [3. **Optional Properties:**](#3-optional-properties) 12 | - [4. **Readonly Properties:**](#4-readonly-properties) 13 | - [5. **Index Signatures:**](#5-index-signatures) 14 | - [6. **Extending Interfaces:**](#6-extending-interfaces) 15 | - [7. **Intersection Types:**](#7-intersection-types) 16 | - [8. **Type Aliases:**](#8-type-aliases) 17 | 18 | ### 1. **Object Literal:** 19 | 20 | You can directly specify the types of properties in an object literal. 21 | 22 | ```tsx 23 | let person: { name: string; age: number } = { name: "John", age: 30 }; 24 | ``` 25 | 26 | ### 2. **Interface:** 27 | 28 | Interfaces are a powerful way to define object types and provide a clear contract for the expected structure of an object. 29 | 30 | ```tsx 31 | interface Person { 32 | name: string; 33 | age: number; 34 | } 35 | 36 | let employee: Person = { name: "Alice", age: 25 }; 37 | ``` 38 | 39 | ### 3. **Optional Properties:** 40 | 41 | You can mark properties as optional using the `?` syntax. 42 | 43 | ```tsx 44 | interface Car { 45 | brand: string; 46 | model?: string; // Optional property 47 | } 48 | 49 | let myCar: Car = { brand: "Toyota" }; 50 | ``` 51 | 52 | ### 4. **Readonly Properties:** 53 | 54 | You can mark properties as readonly using the `readonly` keyword. 55 | 56 | ```tsx 57 | interface Point { 58 | readonly x: number; 59 | readonly y: number; 60 | } 61 | 62 | let coordinates: Point = { x: 1, y: 2 }; 63 | // coordinates.x = 3; // Error: Cannot assign to 'x' because it is a read-only property. 64 | ``` 65 | 66 | ### 5. **Index Signatures:** 67 | 68 | You can use index signatures to define objects with dynamic keys. 69 | 70 | ```tsx 71 | interface Dictionary { 72 | [key: string]: number; 73 | } 74 | 75 | let ages: Dictionary = { 76 | "John": 30, 77 | "Alice": 25, 78 | }; 79 | ``` 80 | 81 | ### 6. **Extending Interfaces:** 82 | 83 | Interfaces can extend other interfaces, allowing you to build on existing definitions. 84 | 85 | ```tsx 86 | interface Shape { 87 | color: string; 88 | } 89 | 90 | interface Square extends Shape { 91 | sideLength: number; 92 | } 93 | 94 | let mySquare: Square = { color: "red", sideLength: 5 }; 95 | ``` 96 | 97 | ### 7. **Intersection Types:** 98 | 99 | You can combine multiple types using intersection types (`&`). 100 | 101 | ```tsx 102 | type Name = { firstName: string }; 103 | type Age = { age: number }; 104 | 105 | let personInfo: Name & Age = { firstName: "John", age: 30 }; 106 | ``` 107 | 108 | ### 8. **Type Aliases:** 109 | 110 | You can use type aliases to create reusable object types. 111 | 112 | ```tsx 113 | type Coordinates = { x: number; y: number }; 114 | 115 | let point: Coordinates = { x: 1, y: 2 }; 116 | ``` 117 | 118 | These are some common ways to define object types in TypeScript. Choosing the right approach depends on the specific requirements of your application and the level of abstraction you want to achieve. Using interfaces is a recommended practice for defining object types in TypeScript because of their expressiveness and the ability to extend and reuse them. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/README.md: -------------------------------------------------------------------------------- 1 | # TypeScript Basics & Basic Types 2 | 3 | ## Introduction 4 | 5 | Welcome to the TypeScript Basics & Basic Types page! 6 | 7 | Explore fundamental TypeScript concepts, from basic types to advanced topics like function types and callbacks, empowering developers to write robust, type-safe code and master TypeScript development. 8 | 9 | ## Table of Contents 10 | 11 | - [Using Types](./Using%20Types.md) 12 | - [TypeScript Types vs JavaScript Types](./TypeScript%20Types%20vs%20JavaScript%20Types.md) 13 | - [Type Casing](./Type%20Casing.md) 14 | - [Working with Numbers, Strings & Booleans](./Working%20with%20Numbers,%20Strings%20&%20Booleans.md) 15 | - [Type Assignment & Type Inference](./Type%20Assignment%20&%20Type%20Inference.md) 16 | - [Understanding Types](./Understanding%20Types.md) 17 | - [Object Types](./Object%20Types.md) 18 | - [Nested Objects & Types](./Nested%20Objects%20&%20Types.md) 19 | - [Arrays Types](./Arrays%20Type.md) 20 | - [Working with Tuples](./Working%20with%20Tuples.md) 21 | - [Working with Enums](./Working%20with%20Enums.md) 22 | - [The "any" Type](./The%20any%20Type.md) 23 | - [Union Types](./Union%20Types.md) 24 | - [Literal Types](./Literal%20Types.md) 25 | - [Type Aliases / Custom Types](./Type%20Aliases%20Custom%20Types.md) 26 | - [Type Aliases & Object Types](./Type%20Aliases%20&%20Object%20Types.md) 27 | - [Core Types & Concepts](./Core%20Types%20&%20Concepts.md) 28 | - [Function Return Types & "void”](./Function%20Return%20Types%20&%20void”.md) 29 | - [Functions as Types](./Functions%20as%20Types.md) 30 | - [Function Types & Callbacks](Function%20Types%20&%20Callbacks.md) 31 | - [Functions & Types](./Functions%20&%20Types.md) 32 | - [The "unknown" Type](./The%20unknown%20Type.md) 33 | - [The "never" Type](./The%20never%20Type.md) -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/The any Type.md: -------------------------------------------------------------------------------- 1 | # The "any" Type 2 | 3 | ## Introduction 4 | 5 | The `any` type is a powerful and flexible type that essentially turns off the type checker for a particular variable. It allows you to assign values of any type to a variable without type checking, and it disables some of the benefits of static typing. While using `any` can be useful in certain situations, it's generally recommended to avoid it whenever possible, as it weakens TypeScript's ability to catch errors at compile-time. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Declaring Variables with "any":**](#1-declaring-variables-with-any) 10 | - [2. **Type Inference with "any":**](#2-type-inference-with-any) 11 | - [3. **Using "any" with Arrays and Objects:**](#3-using-any-with-arrays-and-objects) 12 | - [4. **Dynamic Property Access:**](#4-dynamic-property-access) 13 | - [5. **Function Return Type "any":**](#5-function-return-type-any) 14 | - [6. **Loose Type Checking:**](#6-loose-type-checking) 15 | - [7. **Type Assertion with "any":**](#7-type-assertion-with-any) 16 | - [8. **Combining "any" with Other Types:**](#8-combining-any-with-other-types) 17 | 18 | ### 1. **Declaring Variables with "any":** 19 | 20 | ```tsx 21 | let dynamicValue: any = 42; 22 | dynamicValue = "Hello, TypeScript!"; 23 | dynamicValue = true; 24 | ``` 25 | 26 | ### 2. **Type Inference with "any":** 27 | 28 | ```tsx 29 | let anyValue; // TypeScript infers any type for anyValue 30 | anyValue = 42; // OK 31 | anyValue = "Hello"; // OK 32 | ``` 33 | 34 | ### 3. **Using "any" with Arrays and Objects:** 35 | 36 | ```tsx 37 | let anyArray: any[] = [1, "two", true]; 38 | let anyObject: any = { key: "value", count: 10 }; 39 | ``` 40 | 41 | ### 4. **Dynamic Property Access:** 42 | 43 | ```tsx 44 | let dynamicProperty: any = { key: "value" }; 45 | let propertyValue: any = dynamicProperty.someDynamicKey; 46 | ``` 47 | 48 | ### 5. **Function Return Type "any":** 49 | 50 | ```tsx 51 | function returnValue(): any { 52 | return "Dynamic Value"; 53 | } 54 | ``` 55 | 56 | ### 6. **Loose Type Checking:** 57 | 58 | ```tsx 59 | let value: any = "Hello, TypeScript!"; 60 | let length: number = value.length; // No compile-time error 61 | ``` 62 | 63 | ### 7. **Type Assertion with "any":** 64 | 65 | ```tsx 66 | let stringValue: any = "123"; 67 | let numberValue: number = stringValue; // Type assertion 68 | ``` 69 | 70 | ### 8. **Combining "any" with Other Types:** 71 | 72 | ```tsx 73 | let mixedValue: any = 42 as any as string; // Mixing types 74 | ``` 75 | 76 | While `any` can be helpful in scenarios where the type of a value is truly unknown or difficult to express, it's essential to use it judiciously. Overusing `any` can lead to code that is harder to maintain and debug, as it bypasses TypeScript's benefits of static typing. Whenever possible, try to use more specific types, interfaces, or union types to maintain type safety in your TypeScript code. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/The never Type.md: -------------------------------------------------------------------------------- 1 | # The "never" Type 2 | 3 | ## Introduction 4 | 5 | The `never` type represents a value that never occurs. It is used to denote functions that never return, variables that are never assigned, or expressions that always throw an exception. The `never` type is often employed in scenarios where an operation is expected to result in an unrecoverable error or when control flow should never reach a certain point. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Functions That Never Return:**](#1-functions-that-never-return) 10 | - [2. **Type Guards:**](#2-type-guards) 11 | - [3. **Union Types with "never":**](#3-union-types-with-never) 12 | - [4. **Switch Statements:**](#4-switch-statements) 13 | 14 | ### 1. **Functions That Never Return:** 15 | 16 | ```tsx 17 | function throwError(message: string): never { 18 | throw new Error(message); 19 | } 20 | 21 | function infiniteLoop(): never { 22 | while (true) { 23 | // Infinite loop, never returns 24 | } 25 | } 26 | ``` 27 | 28 | In these examples, the functions explicitly declare a return type of `never` to indicate that they never return a normal value. Instead, they throw an error or run an infinite loop. 29 | 30 | ### 2. **Type Guards:** 31 | 32 | ```tsx 33 | function assertNever(value: never): never { 34 | throw new Error(`Unexpected value: ${value}`); 35 | } 36 | 37 | function processValue(value: string | number): void { 38 | if (typeof value === 'string') { 39 | // Process string 40 | } else if (typeof value === 'number') { 41 | // Process number 42 | } else { 43 | assertNever(value); // Unreachable code, as value cannot be any other type 44 | } 45 | } 46 | ``` 47 | 48 | In this example, the `assertNever` function is used as a type guard to ensure that the function is exhaustive and handles all possible types. If control flow reaches the `assertNever` call, it means a value of an unexpected type was encountered. 49 | 50 | ### 3. **Union Types with "never":** 51 | 52 | ```tsx 53 | type Result = number | string; 54 | 55 | function processResult(result: Result): void { 56 | if (typeof result === 'number') { 57 | // Process number 58 | } else if (typeof result === 'string') { 59 | // Process string 60 | } else { 61 | const exhaustiveCheck: never = result; // Unreachable code 62 | } 63 | } 64 | ``` 65 | 66 | The `never` type is often used in conjunction with union types to ensure that all possible types are handled. 67 | 68 | ### 4. **Switch Statements:** 69 | 70 | ```tsx 71 | type Action = { type: 'add'; value: number } | { type: 'subtract'; value: number }; 72 | 73 | function processAction(action: Action): void { 74 | switch (action.type) { 75 | case 'add': 76 | // Process 'add' action 77 | break; 78 | case 'subtract': 79 | // Process 'subtract' action 80 | break; 81 | default: 82 | const exhaustiveCheck: never = action; // Unreachable code 83 | } 84 | } 85 | ``` 86 | 87 | When using switch statements with discriminated unions, the `never` type can be used to ensure that all cases are handled. 88 | 89 | Using the `never` type appropriately helps make your code more robust and ensures that unexpected scenarios are explicitly handled, improving the overall reliability of your TypeScript code. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/The unknown Type.md: -------------------------------------------------------------------------------- 1 | # The "unknown" Type 2 | 3 | ## Introduction 4 | 5 | The `unknown` type represents a type-safe counterpart to the `any` type. It is used to indicate that the type of a value is unknown during development, providing a safer alternative to using `any`. Unlike `any`, variables of type `unknown` cannot be assigned to other types without explicit type checking or assertion. 6 | 7 | 8 | ## Table of Contents 9 | 10 | - [1. **Declaration and Assignment:**](#1-declaration-and-assignment) 11 | - [2. **Type Checking:**](#2-type-checking) 12 | - [3. **Type Assertion:**](#3-type-assertion) 13 | - [4. **Function Parameters with Unknown:**](#4-function-parameters-with-unknown) 14 | - [5. **Returning "unknown" from a Function:**](#5-returning-unknown-from-a-function) 15 | - [6. **Intersection with Known Types:**](#6-intersection-with-known-types) 16 | 17 | ### 1. **Declaration and Assignment:** 18 | 19 | ```tsx 20 | let userInput: unknown; 21 | 22 | userInput = 5; 23 | userInput = 'Hello, TypeScript!'; 24 | ``` 25 | 26 | In this example, `userInput` is declared with the `unknown` type, and it can be assigned values of different types. 27 | 28 | ### 2. **Type Checking:** 29 | 30 | ```tsx 31 | let userInput: unknown = 'Hello, TypeScript!'; 32 | 33 | if (typeof userInput === 'string') { 34 | let strLength: number = userInput.length; 35 | console.log(strLength); 36 | } 37 | ``` 38 | 39 | Type checking is required before performing operations specific to a certain type. In this case, we check if `userInput` is a string before getting its length. 40 | 41 | ### 3. **Type Assertion:** 42 | 43 | ```tsx 44 | let userInput: unknown = 'Hello, TypeScript!'; 45 | 46 | let strLength: number = (userInput as string).length; 47 | console.log(strLength); 48 | ``` 49 | 50 | Type assertion (`as` syntax) can be used when you are confident about the type. In this example, we assert that `userInput` is a string before getting its length. 51 | 52 | ### 4. **Function Parameters with Unknown:** 53 | 54 | ```tsx 55 | function processInput(input: unknown): void { 56 | if (typeof input === 'string') { 57 | console.log(input.toUpperCase()); 58 | } else { 59 | console.log('Input is not a string'); 60 | } 61 | } 62 | 63 | processInput('Hello, TypeScript!'); 64 | processInput(42); 65 | ``` 66 | 67 | When using `unknown` in function parameters, you can perform type checking inside the function based on the actual type of the argument. 68 | 69 | ### 5. **Returning "unknown" from a Function:** 70 | 71 | ```tsx 72 | function getUserData(): unknown { 73 | // ... 74 | } 75 | 76 | let userData: unknown = getUserData(); 77 | ``` 78 | 79 | Functions can return values of type `unknown` when the specific type is not known until runtime. 80 | 81 | ### 6. **Intersection with Known Types:** 82 | 83 | ```tsx 84 | let userInput: unknown = 'Hello, TypeScript!'; 85 | 86 | let strLength: number = (userInput as string).length; // Type assertion 87 | let upperCaseInput: string = (userInput as string).toUpperCase(); // Type assertion 88 | ``` 89 | 90 | You can intersect `unknown` with known types using type assertions when you are confident about the type. 91 | 92 | Using `unknown` promotes type safety by requiring explicit type checking before performing operations on values of this type. It is a more controlled alternative to using `any`, making your TypeScript code safer and more maintainable. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Type Aliases & Object Types.md: -------------------------------------------------------------------------------- 1 | # Type Aliases & Object Types 2 | 3 | ## Introduction 4 | 5 | Type aliases can be used to create custom names for object types, making the code more readable and maintainable. Here are examples of using type aliases with object types: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Basic Object Type Alias:**](#1-basic-object-type-alias) 10 | - [2. **Union Object Type Alias:**](#2-union-object-type-alias) 11 | - [3. **Object Type Alias with Functions:**](#3-object-type-alias-with-functions) 12 | - [4. **Nested Object Type Alias:**](#4-nested-object-type-alias) 13 | - [5. **Object Type Alias with Generics:**](#5-object-type-alias-with-generics) 14 | - [6. **Mapped Object Type Alias:**](#6-mapped-object-type-alias) 15 | - [7. **Combining Object Type Aliases:**](#7-combining-object-type-aliases) 16 | 17 | ### 1. **Basic Object Type Alias:** 18 | 19 | ```tsx 20 | // Type alias for a simple object type 21 | type Point = { 22 | x: number; 23 | y: number; 24 | }; 25 | 26 | let origin: Point = { x: 0, y: 0 }; 27 | let position: Point = { x: 5, y: 10 }; 28 | ``` 29 | 30 | ### 2. **Union Object Type Alias:** 31 | 32 | ```tsx 33 | // Type alias for a union of object types 34 | type Shape = { 35 | kind: "circle"; 36 | radius: number; 37 | } | { 38 | kind: "square"; 39 | sideLength: number; 40 | }; 41 | 42 | let circle: Shape = { kind: "circle", radius: 5 }; 43 | let square: Shape = { kind: "square", sideLength: 4 }; 44 | 45 | ``` 46 | 47 | ### 3. **Object Type Alias with Functions:** 48 | 49 | ```tsx 50 | // Type alias for an object with a function property 51 | type MathOperations = { 52 | add: (a: number, b: number) => number; 53 | subtract: (a: number, b: number) => number; 54 | }; 55 | 56 | let calculator: MathOperations = { 57 | add: (a, b) => a + b, 58 | subtract: (a, b) => a - b, 59 | }; 60 | ``` 61 | 62 | ### 4. **Nested Object Type Alias:** 63 | 64 | ```tsx 65 | // Nested type alias for a complex object type 66 | type Employee = { 67 | id: number; 68 | name: string; 69 | contact: { 70 | email: string; 71 | phone: string; 72 | }; 73 | }; 74 | 75 | let employee: Employee = { 76 | id: 1, 77 | name: "John Doe", 78 | contact: { 79 | email: "john@example.com", 80 | phone: "123-456-7890", 81 | }, 82 | }; 83 | ``` 84 | 85 | ### 5. **Object Type Alias with Generics:** 86 | 87 | ```tsx 88 | // Type alias for a generic object type 89 | type Pair = { 90 | first: T; 91 | second: T; 92 | }; 93 | 94 | let numberPair: Pair = { first: 1, second: 2 }; 95 | let stringPair: Pair = { first: "one", second: "two" }; 96 | ``` 97 | 98 | ### 6. **Mapped Object Type Alias:** 99 | 100 | ```tsx 101 | // Mapped type alias for making properties readonly 102 | type ReadOnly = { 103 | readonly [K in keyof T]: T[K]; 104 | }; 105 | 106 | type User = { 107 | id: number; 108 | name: string; 109 | }; 110 | 111 | type ReadOnlyUser = ReadOnly; 112 | 113 | let user: ReadOnlyUser = { id: 1, name: "Alice" }; 114 | // user.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property. 115 | ``` 116 | 117 | ### 7. **Combining Object Type Aliases:** 118 | 119 | ```tsx 120 | // Combining object type aliases 121 | type Person = { 122 | name: string; 123 | age: number; 124 | }; 125 | 126 | type Employee = Person & { 127 | employeeId: string; 128 | }; 129 | 130 | let employee: Employee = { name: "John", age: 30, employeeId: "123" }; 131 | ``` 132 | 133 | Using type aliases with object types allows you to create more expressive and reusable type definitions. They are especially useful when dealing with complex data structures, promoting code readability and maintainability. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Type Aliases Custom Types.md: -------------------------------------------------------------------------------- 1 | # Type Aliases / Custom Types 2 | 3 | ## Introduction 4 | 5 | Type aliases (or custom types) allow you to create a named reference for a specific type or combination of types. Type aliases enhance code readability, maintainability, and can simplify complex type expressions. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Basic Type Alias:**](#1-basic-type-alias) 10 | - [2. **Union Type Alias:**](#2-union-type-alias) 11 | - [3. **Object Type Alias:**](#3-object-type-alias) 12 | - [4. **Function Type Alias:**](#4-function-type-alias) 13 | - [5. **Generic Type Alias:**](#5-generic-type-alias) 14 | - [6. **Combining Types with Type Alias:**](#6-combining-types-with-type-alias) 15 | - [7. **Discriminated Union with Type Alias:**](#7-discriminated-union-with-type-alias) 16 | - [8. **Mapped Type Alias:**](#8-mapped-type-alias) 17 | 18 | 19 | ### 1. **Basic Type Alias:** 20 | 21 | ```tsx 22 | // Type alias for a string or number 23 | type ID = string | number; 24 | 25 | let userId: ID = "user123"; 26 | let orderId: ID = 456; 27 | // let productId: ID = true; // Error: Type 'true' is not assignable to type 'ID'. 28 | ``` 29 | 30 | ### 2. **Union Type Alias:** 31 | 32 | ```tsx 33 | // Type alias for a union of string and number 34 | type UserNameOrId = string | number; 35 | 36 | let userName: UserNameOrId = "John"; 37 | let userId: UserNameOrId = 123; 38 | ``` 39 | 40 | ### 3. **Object Type Alias:** 41 | 42 | ```tsx 43 | // Type alias for an object with specific properties 44 | type Point = { x: number; y: number }; 45 | 46 | let origin: Point = { x: 0, y: 0 }; 47 | let position: Point = { x: 5, y: 10 }; 48 | ``` 49 | 50 | ### 4. **Function Type Alias:** 51 | 52 | ```tsx 53 | // Type alias for a function 54 | type MathOperation = (a: number, b: number) => number; 55 | 56 | let add: MathOperation = (a, b) => a + b; 57 | let multiply: MathOperation = (a, b) => a * b; 58 | ``` 59 | 60 | ### 5. **Generic Type Alias:** 61 | 62 | ```tsx 63 | // Generic type alias 64 | type Pair = [T, T]; 65 | 66 | let numberPair: Pair = [1, 2]; 67 | let stringPair: Pair = ["hello", "world"]; 68 | ``` 69 | 70 | ### 6. **Combining Types with Type Alias:** 71 | 72 | ```tsx 73 | // Combining types with type alias 74 | type User = { 75 | id: number; 76 | username: string; 77 | }; 78 | 79 | type AdminUser = User & { isAdmin: boolean }; 80 | 81 | let admin: AdminUser = { id: 1, username: "admin", isAdmin: true }; 82 | ``` 83 | 84 | ### 7. **Discriminated Union with Type Alias:** 85 | 86 | ```tsx 87 | // Discriminated union with type alias 88 | type Circle = { kind: "circle"; radius: number }; 89 | type Square = { kind: "square"; sideLength: number }; 90 | 91 | type Shape = Circle | Square; 92 | 93 | function getArea(shape: Shape): number { 94 | switch (shape.kind) { 95 | case "circle": 96 | return Math.PI * Math.pow(shape.radius, 2); 97 | case "square": 98 | return Math.pow(shape.sideLength, 2); 99 | } 100 | } 101 | ``` 102 | 103 | ### 8. **Mapped Type Alias:** 104 | 105 | ```tsx 106 | // Mapped type alias 107 | type ReadOnly = { 108 | readonly [K in keyof T]: T[K]; 109 | }; 110 | 111 | type User = { 112 | id: number; 113 | name: string; 114 | }; 115 | 116 | type ReadOnlyUser = ReadOnly; 117 | ``` 118 | 119 | Type aliases are especially useful when you need to reuse complex type definitions across your codebase or create more expressive names for types. They provide a way to create custom abstractions and improve the maintainability of your TypeScript code. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Type Assignment & Type Inference.md: -------------------------------------------------------------------------------- 1 | # Type Assignment & Type Inference 2 | 3 | ## Introduction 4 | 5 | Type assignment and type inference play crucial roles in defining and working with variables. Let's explore both concepts: 6 | 7 | ## Table of Contents 8 | 9 | - [1. Type Assignment:](#1-type-assignment) 10 | - [Example:](#example) 11 | - [2. Type Inference:](#2-type-inference) 12 | - [Example:](#example-1) 13 | - [3. Combining Type Assignment and Type Inference:](#3-combining-type-assignment-and-type-inference) 14 | - [Example:](#example-2) 15 | - [4. Function Parameter and Return Type Annotations:](#4-function-parameter-and-return-type-annotations) 16 | - [Example:](#example-3) 17 | 18 | ### 1. Type Assignment: 19 | 20 | Type assignment involves explicitly specifying the type of a variable. This is done using a colon (`:`) followed by the type name. 21 | 22 | ### Example: 23 | 24 | ```tsx 25 | // Type assignment for numbers 26 | let age: number = 25; 27 | 28 | // Type assignment for strings 29 | let name: string = "Alice"; 30 | 31 | // Type assignment for booleans 32 | let isValid: boolean = true; 33 | 34 | // Type assignment for arrays 35 | let numbers: number[] = [1, 2, 3]; 36 | ``` 37 | 38 | ### 2. Type Inference: 39 | 40 | Type inference is a TypeScript feature that automatically determines the type of a variable based on its initialization. When a variable is assigned a value during declaration, TypeScript infers its type without explicit type annotations. 41 | 42 | ### Example: 43 | 44 | ```tsx 45 | // Type inference for numbers 46 | let height = 180; // TypeScript infers the type as number 47 | 48 | // Type inference for strings 49 | let greeting = "Hello"; // TypeScript infers the type as string 50 | 51 | // Type inference for booleans 52 | let isTrue = false; // TypeScript infers the type as boolean 53 | 54 | // Type inference for arrays 55 | let fruits = ["apple", "orange", "banana"]; // TypeScript infers the type as string[] 56 | ``` 57 | 58 | Type inference simplifies code by reducing the need for explicit type annotations. However, explicit type annotations can still be beneficial for clarity and documentation. 59 | 60 | ### 3. Combining Type Assignment and Type Inference: 61 | 62 | In many cases, you might use a combination of type assignment and type inference. 63 | 64 | ### Example: 65 | 66 | ```tsx 67 | // Type assignment with type inference 68 | let employeeId: number = 123; 69 | let employeeName = "John Doe"; // TypeScript infers the type as string 70 | 71 | // Type assignment with complex types 72 | let userDetails: { id: number; name: string } = { 73 | id: employeeId, 74 | name: employeeName, 75 | }; 76 | ``` 77 | 78 | ### 4. Function Parameter and Return Type Annotations: 79 | 80 | Type assignment is commonly used when defining function parameter types and return types. 81 | 82 | ### Example: 83 | 84 | ```tsx 85 | // Function with type annotations 86 | function addNumbers(x: number, y: number): number { 87 | return x + y; 88 | } 89 | 90 | // Type inference for function return type 91 | function multiply(x: number, y: number) { 92 | return x * y; // TypeScript infers the return type as number 93 | } 94 | ``` 95 | 96 | Both type assignment and type inference contribute to the language's static typing features, helping catch potential errors during development and providing better tooling support. Choose the approach that fits the context of your code and enhances readability. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Type Casing.md: -------------------------------------------------------------------------------- 1 | # Type Casing 2 | 3 | ## Introduction 4 | 5 | Type names and type aliases conventionally use PascalCase. PascalCase is a naming convention where the first letter of each word is capitalized, and there are no underscores between words. This convention helps distinguish types from variables and makes the code more readable. Here are some examples: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Interfaces:**](#1-interfaces) 10 | - [2. **Type Aliases:**](#2-type-aliases) 11 | - [3. **Enums:**](#3-enums) 12 | - [4. **Classes:**](#4-classes) 13 | - [5. **Type Parameters (Generics):**](#5-type-parameters-generics) 14 | - [6. **Declaration Files (.d.ts):**](#6-declaration-files-dts) 15 | 16 | ### 1. **Interfaces:** 17 | 18 | - **PascalCase:** 19 | 20 | ```tsx 21 | interface Point { 22 | x: number; 23 | y: number; 24 | } 25 | ``` 26 | 27 | 28 | ### 2. **Type Aliases:** 29 | 30 | - **PascalCase:** 31 | 32 | ```tsx 33 | type EmployeeInfo = { 34 | name: string; 35 | age: number; 36 | }; 37 | ``` 38 | 39 | 40 | ### 3. **Enums:** 41 | 42 | - **PascalCase:** 43 | 44 | ```tsx 45 | enum Color { 46 | Red, 47 | Green, 48 | Blue 49 | } 50 | ``` 51 | 52 | 53 | ### 4. **Classes:** 54 | 55 | - **PascalCase for Class Names:** 56 | 57 | ```tsx 58 | class Car { 59 | // class members here 60 | } 61 | ``` 62 | 63 | 64 | ### 5. **Type Parameters (Generics):** 65 | 66 | - **Single Letter in PascalCase:** 67 | 68 | ```tsx 69 | function identity(value: T): T { 70 | return value; 71 | } 72 | ``` 73 | 74 | 75 | ### 6. **Declaration Files (.d.ts):** 76 | 77 | - **PascalCase for Module and Type Names:** 78 | 79 | ```tsx 80 | // example.d.ts 81 | declare module "ExampleLibrary" { 82 | function myFunction(value: string): number; 83 | } 84 | ``` 85 | 86 | 87 | This consistent naming convention enhances code readability and maintains a clear distinction between types and variables or functions in your TypeScript code. It's important to follow these conventions for consistency and to make your code more accessible to other developers who might work on the project. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/TypeScript Types vs JavaScript Types.md: -------------------------------------------------------------------------------- 1 | # TypeScript Types vs JavaScript Types 2 | 3 | ## Introduction 4 | 5 | TypeScript and JavaScript share some common types as both languages are designed to be compatible. However, TypeScript introduces additional features and concepts related to types that go beyond what is available in JavaScript. Here's a comparison between TypeScript types and JavaScript types: 6 | 7 | ## Table of Contents 8 | 9 | - [Common Types in TypeScript and JavaScript:](#common-types-in-typescript-and-javascript) 10 | - [Additional TypeScript Types and Features:](#additional-typescript-types-and-features) 11 | 12 | ### Common Types in TypeScript and JavaScript: 13 | 14 | 1. **Primitive Types:** 15 | - **JavaScript:** 16 | 17 | ```jsx 18 | let num = 5; // Number 19 | let str = "Hello"; // String 20 | let bool = true; // Boolean 21 | ``` 22 | 23 | - **TypeScript:** 24 | 25 | ```tsx 26 | let num: number = 5; 27 | let str: string = "Hello"; 28 | let bool: boolean = true; 29 | ``` 30 | 31 | 2. **Object:** 32 | - **JavaScript:** 33 | 34 | ```jsx 35 | let obj = { key: "value" }; 36 | ``` 37 | 38 | - **TypeScript:** 39 | 40 | ```tsx 41 | let obj: { key: string } = { key: "value" }; 42 | ``` 43 | 44 | 3. **Arrays:** 45 | - **JavaScript:** 46 | 47 | ```jsx 48 | let arr = [1, 2, 3]; 49 | ``` 50 | 51 | - **TypeScript:** 52 | 53 | ```tsx 54 | let arr: number[] = [1, 2, 3]; 55 | ``` 56 | 57 | 58 | ### Additional TypeScript Types and Features: 59 | 60 | 1. **Union Types:** 61 | - **TypeScript:** 62 | 63 | ```tsx 64 | let value: number | string; 65 | value = 10; // Valid 66 | value = "Hello"; // Valid 67 | ``` 68 | 69 | 2. **Type Aliases:** 70 | - **TypeScript:** 71 | 72 | ```tsx 73 | type Point = { x: number; y: number }; 74 | let p: Point = { x: 1, y: 2 }; 75 | ``` 76 | 77 | 3. **Interfaces:** 78 | - **TypeScript:** 79 | 80 | ```tsx 81 | interface Person { 82 | name: string; 83 | age: number; 84 | } 85 | let person: Person = { name: "John", age: 30 }; 86 | ``` 87 | 88 | 4. **Enums:** 89 | - **TypeScript:** 90 | 91 | ```tsx 92 | enum Color { 93 | Red, 94 | Green, 95 | Blue 96 | } 97 | let myColor: Color = Color.Green; 98 | ``` 99 | 100 | 5. **Function Types:** 101 | - **TypeScript:** 102 | 103 | ```tsx 104 | type AddFunction = (a: number, b: number) => number; 105 | let add: AddFunction = (a, b) => a + b; 106 | ``` 107 | 108 | 6. **Generics:** 109 | - **TypeScript:** 110 | 111 | ```tsx 112 | function identity(arg: T): T { 113 | return arg; 114 | } 115 | let result: number = identity(10); 116 | ``` 117 | 118 | 7. **Nullable Types:** 119 | - **TypeScript:** 120 | 121 | ```tsx 122 | let value: number | null = null; 123 | ``` 124 | 125 | 8. **Type Assertion:** 126 | - **TypeScript:** 127 | 128 | ```tsx 129 | let variable: any = "Hello, TypeScript!"; 130 | let length: number = (variable as string).length; 131 | ``` 132 | 133 | 9. **Declaration Files (.d.ts):** 134 | - **TypeScript:** 135 | 136 | ```tsx 137 | // example.d.ts 138 | declare module "example-library" { 139 | function myFunction(value: string): number; 140 | } 141 | ``` 142 | 143 | 144 | These additional TypeScript features provide more expressive power, enhance code readability, and catch errors during development, leading to more maintainable and robust codebases compared to JavaScript alone. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Understanding Types.md: -------------------------------------------------------------------------------- 1 | # Understanding Types 2 | 3 | ## Introduction 4 | 5 | Understanding types in TypeScript is fundamental to leveraging the language's static typing features. TypeScript provides a way to describe the shape and behavior of values, making it more robust and maintainable. Let's explore key concepts related to types in TypeScript: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Basic Types:**](#1-basic-types) 10 | - [a. **Number:**](#a-number) 11 | - [b. **String:**](#b-string) 12 | - [c. **Boolean:**](#c-boolean) 13 | - [d. **Array:**](#d-array) 14 | - [2. **Object Types:**](#2-object-types) 15 | - [a. **Object Literal:**](#a-object-literal) 16 | - [b. **Interface:**](#b-interface) 17 | - [3. **Union and Intersection Types:**](#3-union-and-intersection-types) 18 | - [a. **Union Types:**](#a-union-types) 19 | - [b. **Intersection Types:**](#b-intersection-types) 20 | - [4. **Function Types:**](#4-function-types) 21 | - [a. **Function Parameter and Return Types:**](#a-function-parameter-and-return-types) 22 | - [5. **Generics:**](#5-generics) 23 | - [a. **Generic Function:**](#a-generic-function) 24 | - [6. **Type Aliases:**](#6-type-aliases) 25 | - [a. **Creating Custom Types:**](#a-creating-custom-types) 26 | - [7. **Type Assertion:**](#7-type-assertion) 27 | - [a. **Explicit Type Conversion:**](#a-explicit-type-conversion) 28 | - [8. **Declaration Files (.d.ts):**](#8-declaration-files-dts) 29 | - [a. **Defining Types for External Modules:**](#a-defining-types-for-external-modules) 30 | 31 | ### 1. **Basic Types:** 32 | 33 | ### a. **Number:** 34 | 35 | ```tsx 36 | let age: number = 25; 37 | ``` 38 | 39 | ### b. **String:** 40 | 41 | ```tsx 42 | let name: string = "Alice"; 43 | ``` 44 | 45 | ### c. **Boolean:** 46 | 47 | ```tsx 48 | let isValid: boolean = true; 49 | ``` 50 | 51 | ### d. **Array:** 52 | 53 | ```tsx 54 | let numbers: number[] = [1, 2, 3]; 55 | ``` 56 | 57 | ### 2. **Object Types:** 58 | 59 | ### a. **Object Literal:** 60 | 61 | ```tsx 62 | let person: { name: string; age: number } = { name: "John", age: 30 }; 63 | ``` 64 | 65 | ### b. **Interface:** 66 | 67 | ```tsx 68 | interface Person { 69 | name: string; 70 | age: number; 71 | } 72 | 73 | let employee: Person = { name: "Alice", age: 25 }; 74 | ``` 75 | 76 | ### 3. **Union and Intersection Types:** 77 | 78 | ### a. **Union Types:** 79 | 80 | ```tsx 81 | let result: number | string = 10; 82 | result = "Success"; 83 | ``` 84 | 85 | ### b. **Intersection Types:** 86 | 87 | ```tsx 88 | type Name = { firstName: string }; 89 | type Age = { age: number }; 90 | 91 | let personInfo: Name & Age = { firstName: "John", age: 30 }; 92 | ``` 93 | 94 | ### 4. **Function Types:** 95 | 96 | ### a. **Function Parameter and Return Types:** 97 | 98 | ```tsx 99 | function add(x: number, y: number): number { 100 | return x + y; 101 | } 102 | ``` 103 | 104 | ### 5. **Generics:** 105 | 106 | ### a. **Generic Function:** 107 | 108 | ```tsx 109 | function identity(value: T): T { 110 | return value; 111 | } 112 | 113 | let result: number = identity(10); 114 | ``` 115 | 116 | ### 6. **Type Aliases:** 117 | 118 | ### a. **Creating Custom Types:** 119 | 120 | ```tsx 121 | type Point = { x: number; y: number }; 122 | 123 | let coordinates: Point = { x: 1, y: 2 }; 124 | ``` 125 | 126 | ### 7. **Type Assertion:** 127 | 128 | ### a. **Explicit Type Conversion:** 129 | 130 | ```tsx 131 | let strLength: number = ("Hello").length; 132 | ``` 133 | 134 | ### 8. **Declaration Files (.d.ts):** 135 | 136 | ### a. **Defining Types for External Modules:** 137 | 138 | ```tsx 139 | // example.d.ts 140 | declare module "example-library" { 141 | function myFunction(value: string): number; 142 | } 143 | ``` 144 | 145 | Understanding these types and concepts allows you to create more expressive and error-resistant TypeScript code. TypeScript's static typing helps catch potential issues during development, making your codebase more robust and maintainable. Choose the appropriate type based on the context and requirements of your code. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Union Types.md: -------------------------------------------------------------------------------- 1 | # Union Types 2 | 3 | ## Introduction 4 | 5 | Union types allow you to express a value that can have one of several types. This provides flexibility when a variable or parameter can accept multiple types. Union types are denoted by the `|` (pipe) symbol. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Basic Union Type:**](#1-basic-union-type) 10 | - [2. **Union Type in Function Parameters:**](#2-union-type-in-function-parameters) 11 | - [3. **Union Types with Arrays:**](#3-union-types-with-arrays) 12 | - [4. **Union Types in Object Properties:**](#4-union-types-in-object-properties) 13 | - [5. **Union Types with Type Guard:**](#5-union-types-with-type-guard) 14 | - [6. **Union Types with Enums:**](#6-union-types-with-enums) 15 | - [7. **Union Types in Type Aliases:**](#7-union-types-in-type-aliases) 16 | 17 | ### 1. **Basic Union Type:** 18 | 19 | ```tsx 20 | // A variable that can be either a number or a string 21 | let ageOrName: number | string; 22 | ageOrName = 25; // OK 23 | ageOrName = "John"; // OK 24 | // ageOrName = true; // Error: Type 'boolean' is not assignable to type 'number | string'. 25 | ``` 26 | 27 | ### 2. **Union Type in Function Parameters:** 28 | 29 | ```tsx 30 | // Function parameter that can be either a number or a string 31 | function displayData(data: number | string): void { 32 | console.log(data); 33 | } 34 | 35 | displayData(42); // OK 36 | displayData("Hello"); // OK 37 | // displayData(true); // Error: Type 'boolean' is not assignable to type 'number | string'. 38 | ``` 39 | 40 | ### 3. **Union Types with Arrays:** 41 | 42 | ```tsx 43 | // Array that can contain either numbers or strings 44 | let numericOrStringArray: (number | string)[] = [1, "two", 3, "four"]; 45 | ``` 46 | 47 | ### 4. **Union Types in Object Properties:** 48 | 49 | ```tsx 50 | // Object with properties of different types 51 | interface Person { 52 | name: string; 53 | age: number | string; 54 | } 55 | 56 | let john: Person = { name: "John", age: 25 }; 57 | let alice: Person = { name: "Alice", age: "unknown" }; 58 | ``` 59 | 60 | ### 5. **Union Types with Type Guard:** 61 | 62 | ```tsx 63 | // Using typeof to perform type guard 64 | function printData(data: number | string): void { 65 | if (typeof data === "number") { 66 | console.log("It's a number:", data); 67 | } else { 68 | console.log("It's a string:", data); 69 | } 70 | } 71 | 72 | printData(42); // It's a number: 42 73 | printData("Hello"); // It's a string: Hello 74 | ``` 75 | 76 | ### 6. **Union Types with Enums:** 77 | 78 | ```tsx 79 | // Union type with enums 80 | enum Shape { 81 | Circle, 82 | Square, 83 | } 84 | 85 | function getArea(shape: Shape | null): number { 86 | switch (shape) { 87 | case Shape.Circle: 88 | return Math.PI * Math.pow(2, 2); 89 | case Shape.Square: 90 | return Math.pow(4, 2); 91 | default: 92 | return 0; 93 | } 94 | } 95 | 96 | console.log(getArea(Shape.Circle)); // Output: 12.566370614359172 97 | ``` 98 | 99 | ### 7. **Union Types in Type Aliases:** 100 | 101 | ```tsx 102 | // Type alias with union type 103 | type Result = string | number; 104 | 105 | let result1: Result = "Success"; 106 | let result2: Result = 42; 107 | ``` 108 | 109 | Union types provide a way to express more flexible and dynamic type scenarios in TypeScript. It's important to use them judiciously and consider type guards or other techniques when working with variables that have union types to maintain type safety. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Using Types.md: -------------------------------------------------------------------------------- 1 | # Using Types 2 | 3 | ## Introduction 4 | 5 | The use of types is a fundamental aspect of the language, and it's one of the key features that differentiates TypeScript from JavaScript. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Type Annotations:**](#1-type-annotations) 10 | - [2. **Function Parameters and Return Types:**](#2-function-parameters-and-return-types) 11 | - [3. **Interfaces:**](#3-interfaces) 12 | - [4. **Arrays and Generics:**](#4-arrays-and-generics) 13 | - [5. **Union and Intersection Types:**](#5-union-and-intersection-types) 14 | - [6. **Type Aliases:**](#6-type-aliases) 15 | - [7. **Enums:**](#7-enums) 16 | - [8. **Classes:**](#8-classes) 17 | - [9. **Type Assertion:**](#9-type-assertion) 18 | - [10. **Declaration Files (.d.ts):**](#10-declaration-files-dts) 19 | 20 | 21 | ### 1. **Type Annotations:** 22 | 23 | - You can explicitly declare the type of a variable using type annotations. For example: 24 | 25 | ```tsx 26 | let name: string = "John"; 27 | let age: number = 25; 28 | ``` 29 | 30 | 31 | ### 2. **Function Parameters and Return Types:** 32 | 33 | - Specify the types of function parameters and return values: 34 | 35 | ```tsx 36 | function add(x: number, y: number): number { 37 | return x + y; 38 | } 39 | ``` 40 | 41 | 42 | ### 3. **Interfaces:** 43 | 44 | - Use interfaces to define the shape of objects: 45 | 46 | ```tsx 47 | interface Person { 48 | name: string; 49 | age: number; 50 | } 51 | 52 | let person: Person = { 53 | name: "Alice", 54 | age: 30 55 | }; 56 | ``` 57 | 58 | 59 | ### 4. **Arrays and Generics:** 60 | 61 | - Use generics to create reusable components with dynamic types: 62 | 63 | ```tsx 64 | let numbers: Array = [1, 2, 3, 4]; 65 | ``` 66 | 67 | 68 | ### 5. **Union and Intersection Types:** 69 | 70 | - Combine types using unions or intersections: 71 | 72 | ```tsx 73 | type Status = "success" | "error"; 74 | type Result = { value: number } & { message: string }; 75 | ``` 76 | 77 | 78 | ### 6. **Type Aliases:** 79 | 80 | - Create your own custom types with type aliases: 81 | 82 | ```tsx 83 | type Point = { 84 | x: number; 85 | y: number; 86 | }; 87 | ``` 88 | 89 | 90 | ### 7. **Enums:** 91 | 92 | - Use enums to define a set of named constants: 93 | 94 | ```tsx 95 | enum Color { 96 | Red, 97 | Green, 98 | Blue 99 | } 100 | 101 | let myColor: Color = Color.Green; 102 | ``` 103 | 104 | 105 | ### 8. **Classes:** 106 | 107 | - Define classes with typed properties and methods: 108 | 109 | ```tsx 110 | class Dog { 111 | name: string; 112 | 113 | constructor(name: string) { 114 | this.name = name; 115 | } 116 | 117 | bark(): void { 118 | console.log("Woof!"); 119 | } 120 | } 121 | 122 | let myDog: Dog = new Dog("Buddy"); 123 | ``` 124 | 125 | 126 | ### 9. **Type Assertion:** 127 | 128 | - Use type assertion to explicitly specify a type when TypeScript cannot infer it: 129 | 130 | ```tsx 131 | let myVariable: any = "Hello, TypeScript!"; 132 | let stringLength: number = (myVariable as string).length; 133 | ``` 134 | 135 | 136 | ### 10. **Declaration Files (.d.ts):** 137 | 138 | - Use declaration files to provide type information for external libraries or JavaScript code: 139 | 140 | ```tsx 141 | // example.d.ts 142 | declare module "example-library" { 143 | function myFunction(value: string): number; 144 | } 145 | ``` 146 | 147 | These are just a few examples of how you can use types in TypeScript. Types provide a powerful way to catch errors early in the development process, improve code documentation, and enable better tooling support in modern development environments. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Working with Enums.md: -------------------------------------------------------------------------------- 1 | # Working with Enums 2 | 3 | ## Introduction 4 | 5 | Enums (enumerations) in TypeScript allow you to define a set of named constant values representing discrete elements or categories. Enumerations make your code more readable and maintainable by providing meaningful names for specific values. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Numeric Enums:**](#1-numeric-enums) 10 | - [2. **String Enums:**](#2-string-enums) 11 | - [3. **Accessing Enum Values:**](#3-accessing-enum-values) 12 | - [4. **Enums with Explicit Values:**](#4-enums-with-explicit-values) 13 | - [5. **Reverse Mapping:**](#5-reverse-mapping) 14 | - [6. **Heterogeneous Enums:**](#6-heterogeneous-enums) 15 | - [7. **Const Enums:**](#7-const-enums) 16 | - [8. **Enums in Functions:**](#8-enums-in-functions) 17 | 18 | ### 1. **Numeric Enums:** 19 | 20 | Numeric enums assign numeric values to each member, starting from 0 by default. 21 | 22 | ```tsx 23 | enum Direction { 24 | Up, // 0 25 | Down, // 1 26 | Left, // 2 27 | Right, // 3 28 | } 29 | 30 | let myDirection: Direction = Direction.Up; 31 | console.log(myDirection); // Output: 0 32 | ``` 33 | 34 | ### 2. **String Enums:** 35 | 36 | String enums allow you to use strings instead of numbers for enum values. 37 | 38 | ```tsx 39 | enum Color { 40 | Red = "RED", 41 | Green = "GREEN", 42 | Blue = "BLUE", 43 | } 44 | 45 | let myColor: Color = Color.Green; 46 | console.log(myColor); // Output: "GREEN" 47 | ``` 48 | 49 | ### 3. **Accessing Enum Values:** 50 | 51 | You can access enum values by their names or numeric values. 52 | 53 | ```tsx 54 | console.log(Direction.Up); // Output: 0 55 | console.log(Direction[2]); // Output: "Left" 56 | console.log(Color.Red); // Output: "RED" 57 | ``` 58 | 59 | ### 4. **Enums with Explicit Values:** 60 | 61 | You can assign explicit values to enum members. 62 | 63 | ```tsx 64 | enum StatusCode { 65 | OK = 200, 66 | NotFound = 404, 67 | InternalServerError = 500, 68 | } 69 | 70 | let status: StatusCode = StatusCode.OK; 71 | console.log(status); // Output: 200 72 | ``` 73 | 74 | ### 5. **Reverse Mapping:** 75 | 76 | Enums support reverse mapping, allowing you to get the name of an enum member from its value. 77 | 78 | ```tsx 79 | console.log(Direction[0]); // Output: "Up" 80 | console.log(Color["GREEN"]); // Output: "Green" 81 | console.log(StatusCode[404]); // Output: "NotFound" 82 | ``` 83 | 84 | ### 6. **Heterogeneous Enums:** 85 | 86 | You can mix numeric and string values in a single enum. 87 | 88 | ```tsx 89 | enum MixedEnum { 90 | A = 1, 91 | B = "B", 92 | C = 3, 93 | } 94 | 95 | let mixedValue: MixedEnum = MixedEnum.B; 96 | console.log(mixedValue); // Output: "B" 97 | ``` 98 | 99 | ### 7. **Const Enums:** 100 | 101 | Using the `const` modifier makes TypeScript replace enum references with their literal values during compilation. 102 | 103 | ```tsx 104 | const enum Size { 105 | Small, 106 | Medium, 107 | Large, 108 | } 109 | 110 | let itemSize: Size = Size.Medium; 111 | // During compilation, the above line is transformed to: 112 | // let itemSize = 1; 113 | ``` 114 | 115 | ### 8. **Enums in Functions:** 116 | 117 | Enums are commonly used to improve readability in functions. 118 | 119 | ```tsx 120 | enum TrafficLight { 121 | Red, 122 | Yellow, 123 | Green, 124 | } 125 | 126 | function getTrafficLightColor(color: TrafficLight): string { 127 | switch (color) { 128 | case TrafficLight.Red: 129 | return "Stop"; 130 | case TrafficLight.Yellow: 131 | return "Proceed with caution"; 132 | case TrafficLight.Green: 133 | return "Go"; 134 | default: 135 | return "Unknown"; 136 | } 137 | } 138 | 139 | let currentColor: TrafficLight = TrafficLight.Green; 140 | console.log(getTrafficLightColor(currentColor)); // Output: "Go" 141 | ``` 142 | 143 | Enums provide a way to define a set of named values and enhance code readability by using meaningful names instead of raw numbers or strings. Choose the appropriate type of enum (numeric, string, etc.) based on your specific use case. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Working with Numbers, Strings & Booleans.md: -------------------------------------------------------------------------------- 1 | # Working with Numbers, Strings & Booleans 2 | 3 | ## Introduction 4 | 5 | Working with numbers, strings, and booleans is similar to JavaScript, but TypeScript allows you to define types explicitly. Here are some examples: 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Numbers:**](#1-numbers) 10 | - [2. **Strings:**](#2-strings) 11 | - [3. **Booleans:**](#3-booleans) 12 | - [4. **Type Annotations for Function Parameters and Return Types:**](#4-type-annotations-for-function-parameters-and-return-types) 13 | - [5. **Type Inference in Functions:**](#5-type-inference-in-functions) 14 | - [6. **Type Assertion:**](#6-type-assertion) 15 | 16 | ### 1. **Numbers:** 17 | 18 | ```tsx 19 | // Explicitly defining the type 20 | let age: number = 25; 21 | 22 | // Operations with numbers 23 | let sum: number = 10 + 5; 24 | let product: number = 3 * 4; 25 | 26 | // Type inference 27 | let height = 180; // TypeScript infers the type as number 28 | ``` 29 | 30 | ### 2. **Strings:** 31 | 32 | ```tsx 33 | // Explicitly defining the type 34 | let message: string = "Hello, TypeScript!"; 35 | 36 | // Concatenation 37 | let greeting: string = "Hi"; 38 | let name: string = "Alice"; 39 | let fullMessage: string = greeting + ", " + name; 40 | 41 | // Template literals 42 | let templateMessage: string = `Hello, ${name}!`; 43 | ``` 44 | 45 | ### 3. **Booleans:** 46 | 47 | ```tsx 48 | // Explicitly defining the type 49 | let isValid: boolean = true; 50 | 51 | // Conditional statements 52 | if (isValid) { 53 | console.log("It's valid."); 54 | } else { 55 | console.log("It's not valid."); 56 | } 57 | 58 | // Type inference 59 | let isTrue = false; // TypeScript infers the type as boolean 60 | ``` 61 | 62 | ### 4. **Type Annotations for Function Parameters and Return Types:** 63 | 64 | ```tsx 65 | // Function with number parameters and return type 66 | function addNumbers(x: number, y: number): number { 67 | return x + y; 68 | } 69 | 70 | // Function with string parameters and return type 71 | function concatenateStrings(str1: string, str2: string): string { 72 | return str1 + str2; 73 | } 74 | 75 | // Function with boolean parameters and return type 76 | function isAdult(age: number): boolean { 77 | return age >= 18; 78 | } 79 | ``` 80 | 81 | ### 5. **Type Inference in Functions:** 82 | 83 | ```tsx 84 | // TypeScript infers the parameter and return types 85 | function multiply(x: number, y: number) { 86 | return x * y; 87 | } 88 | let result: number = multiply(3, 4); // result is inferred as number 89 | ``` 90 | 91 | ### 6. **Type Assertion:** 92 | 93 | ```tsx 94 | // Type assertion for variables 95 | let strLength: number = ("Hello").length; 96 | 97 | // Type assertion for values 98 | let value: any = "World"; 99 | let valueLength: number = (value as string).length; 100 | ``` 101 | 102 | It's important to note that TypeScript provides the benefit of static typing, allowing you to catch potential errors during development. Explicitly defining types helps improve code readability and maintainability. The examples above demonstrate how to work with numbers, strings, and booleans while leveraging TypeScript's type system. -------------------------------------------------------------------------------- /TypeScript Basics & Basic Types/Working with Tuples.md: -------------------------------------------------------------------------------- 1 | # Working with Tuples 2 | 3 | ## Introduction 4 | 5 | Tuples are a specific type that allows you to express an array where the type of each element is known. Tuples are similar to arrays but provide a fixed-length and ordered sequence of elements. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Basic Tuple:**](#1-basic-tuple) 10 | - [2. **Accessing Elements:**](#2-accessing-elements) 11 | - [3. **Updating Elements:**](#3-updating-elements) 12 | - [4. **Tuple Destructuring:**](#4-tuple-destructuring) 13 | - [5. **Function Returning Tuple:**](#5-function-returning-tuple) 14 | - [6. **Optional Elements in Tuple:**](#6-optional-elements-in-tuple) 15 | - [7. **Rest Elements in Tuple:**](#7-rest-elements-in-tuple) 16 | - [8. **Readonly Tuple:**](#8-readonly-tuple) 17 | - [9. **Tuple Type Assertion:**](#9-tuple-type-assertion) 18 | - [10. **Mapped Types with Tuple:**](#10-mapped-types-with-tuple) 19 | 20 | ### 1. **Basic Tuple:** 21 | 22 | ```tsx 23 | // Tuple with specified types 24 | let person: [string, number, boolean] = ["John", 30, true]; 25 | ``` 26 | 27 | ### 2. **Accessing Elements:** 28 | 29 | ```tsx 30 | // Accessing elements by index 31 | let name: string = person[0]; // "John" 32 | let age: number = person[1]; // 30 33 | let isActive: boolean = person[2]; // true 34 | ``` 35 | 36 | ### 3. **Updating Elements:** 37 | 38 | ```tsx 39 | // Updating elements by index 40 | person[1] = 31; // Now, age is 31 41 | ``` 42 | 43 | ### 4. **Tuple Destructuring:** 44 | 45 | ```tsx 46 | // Destructuring tuple elements 47 | let [userName, userAge, isActiveStatus] = person; 48 | ``` 49 | 50 | ### 5. **Function Returning Tuple:** 51 | 52 | ```tsx 53 | // Function returning a tuple 54 | function getUser(): [string, number] { 55 | return ["John", 30]; 56 | } 57 | 58 | let [returnedName, returnedAge] = getUser(); 59 | 60 | ``` 61 | 62 | ### 6. **Optional Elements in Tuple:** 63 | 64 | ```tsx 65 | // Tuple with optional elements 66 | let contact: [string, string?] = ["John"]; 67 | ``` 68 | 69 | ### 7. **Rest Elements in Tuple:** 70 | 71 | ```tsx 72 | // Tuple with rest elements 73 | let team: [string, ...string[]] = ["Alice", "Bob", "Charlie"]; 74 | ``` 75 | 76 | ### 8. **Readonly Tuple:** 77 | 78 | ```tsx 79 | // Readonly tuple 80 | let readonlyTuple: readonly [string, number] = ["John", 30]; 81 | // readonlyTuple[0] = "Alice"; // Error: Index signature in type 'readonly [string, number]' only permits reading. 82 | ``` 83 | 84 | ### 9. **Tuple Type Assertion:** 85 | 86 | ```tsx 87 | // Tuple type assertion 88 | let anyTuple: any[] = ["John", 30]; 89 | let typedTuple: [string, number] = anyTuple as [string, number]; 90 | ``` 91 | 92 | ### 10. **Mapped Types with Tuple:** 93 | 94 | ```tsx 95 | // Mapped types with tuples 96 | type ReadOnlyTuple = { readonly [K in keyof T]: T[K] }; 97 | 98 | let readOnlyPerson: ReadOnlyTuple<[string, number, boolean]> = ["John", 30, true]; 99 | // readOnlyPerson[0] = "Alice"; // Error: Index signature in type 'readonly [string, number, boolean]' only permits reading. 100 | ``` 101 | 102 | Tuples are particularly useful when working with functions that return multiple values or when the order and type of elements in an array are fixed. Leverage the features provided by tuples to enhance type safety in your TypeScript code. -------------------------------------------------------------------------------- /TypeScript Compiler/Compiling the Entire Project Multiple Files.md: -------------------------------------------------------------------------------- 1 | # Compiling the Entire Project / Multiple Files 2 | 3 | ## Introduction 4 | 5 | When compiling a TypeScript project that consists of multiple files, you can use the TypeScript compiler (`tsc`) to process the entire project. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Organize Project Structure:**](#1-organize-project-structure) 10 | - [2. **Create tsconfig.json:**](#2-create-tsconfigjson) 11 | - [3. **Run the TypeScript Compiler:**](#3-run-the-typescript-compiler) 12 | - [4. **Check the Output:**](#4-check-the-output) 13 | - [5. **Run Compiled JavaScript:**](#5-run-compiled-javascript) 14 | - [6. **Watch Mode (Optional):**](#6-watch-mode-optional) 15 | 16 | 17 | ### 1. **Organize Project Structure:** 18 | 19 | Ensure that your TypeScript files are organized in a logical directory structure. It's common to use a dedicated folder (e.g., `src`) for your TypeScript source files. 20 | 21 | Example project structure: 22 | 23 | ``` 24 | my-project/ 25 | ├── src/ 26 | │ ├── main.ts 27 | │ ├── utils/ 28 | │ │ ├── math.ts 29 | │ │ └── string.ts 30 | │ └── components/ 31 | │ ├── button.ts 32 | │ └── input.ts 33 | └── tsconfig.json 34 | ``` 35 | 36 | ### 2. **Create tsconfig.json:** 37 | 38 | Create a `tsconfig.json` file in the root of your project to configure TypeScript compilation options. Here's a minimal example: 39 | 40 | ```json 41 | { 42 | "compilerOptions": { 43 | "target": "es5", 44 | "module": "commonjs", 45 | "outDir": "./dist", 46 | "rootDir": "./src", 47 | "strict": true 48 | }, 49 | "include": ["src/**/*.ts"], 50 | "exclude": ["node_modules"] 51 | } 52 | ``` 53 | 54 | - `"outDir"`: Specifies the output directory for compiled JavaScript files. 55 | - `"rootDir"`: Indicates the root directory of TypeScript source files. 56 | - `"include"`: An array of file patterns to include in compilation. 57 | - `"exclude"`: An array of file patterns to exclude from compilation. 58 | 59 | ### 3. **Run the TypeScript Compiler:** 60 | 61 | Open a terminal, navigate to the project's root directory, and run the TypeScript compiler using the `tsc` command: 62 | 63 | ```bash 64 | tsc 65 | ``` 66 | 67 | This command compiles the entire project based on the settings in the `tsconfig.json` file. 68 | 69 | ### 4. **Check the Output:** 70 | 71 | After compilation, you should see the generated JavaScript files in the specified `outDir` (e.g., `dist` in the example). The directory structure within `outDir` mirrors the structure of your `src` directory. 72 | 73 | Example output: 74 | 75 | ``` 76 | my-project/ 77 | ├── dist/ 78 | │ ├── main.js 79 | │ ├── utils/ 80 | │ │ ├── math.js 81 | │ │ └── string.js 82 | │ └── components/ 83 | │ ├── button.js 84 | │ └── input.js 85 | └── tsconfig.json 86 | ``` 87 | 88 | ### 5. **Run Compiled JavaScript:** 89 | 90 | You can now run the compiled JavaScript files using the appropriate runtime environment (e.g., Node.js for server-side code or a browser for client-side code). 91 | 92 | For example, if using Node.js: 93 | 94 | ```bash 95 | node dist/main.js 96 | ``` 97 | 98 | ### 6. **Watch Mode (Optional):** 99 | 100 | To enable continuous compilation in watch mode (recompiling on file changes), use the `--watch` flag: 101 | 102 | ```bash 103 | tsc --watch 104 | ``` 105 | 106 | This is useful during development when you want the compiler to automatically update the output when you save changes to your TypeScript files. 107 | 108 | By following these steps, you can compile a TypeScript project with multiple files. Adjust the `tsconfig.json` settings based on your project's requirements. -------------------------------------------------------------------------------- /TypeScript Compiler/Including & Excluding Files.md: -------------------------------------------------------------------------------- 1 | # Including & Excluding Files 2 | 3 | ## Introduction 4 | 5 | You can control which files are included or excluded from compilation using the `"include"` and `"exclude"` options in the `tsconfig.json` configuration file. 6 | 7 | ### Including Files: 8 | 9 | The `"include"` option specifies an array of file globs that determine which files should be included in the compilation. Here's an example: 10 | 11 | ```json 12 | { 13 | "compilerOptions": { 14 | // Compiler options... 15 | }, 16 | "include": [ 17 | "src/**/*.ts", 18 | "tests/**/*.ts" 19 | ] 20 | } 21 | ``` 22 | 23 | In this example, TypeScript will include all `.ts` files under the `src` and `tests` directories and their subdirectories in the compilation process. 24 | 25 | ### Excluding Files: 26 | 27 | The `"exclude"` option specifies an array of file globs for files that should be excluded from compilation. Here's an example: 28 | 29 | ```json 30 | { 31 | "compilerOptions": { 32 | // Compiler options... 33 | }, 34 | "exclude": [ 35 | "node_modules", 36 | "build" 37 | ] 38 | } 39 | ``` 40 | 41 | In this example, TypeScript will exclude all files under the `node_modules` and `build` directories from the compilation. 42 | 43 | ### Using Both `"include"` and `"exclude"`: 44 | 45 | You can use both `"include"` and `"exclude"` options together. When both options are specified, TypeScript first includes files based on the `"include"` patterns and then excludes files based on the `"exclude"` patterns. Here's an example: 46 | 47 | ```json 48 | { 49 | "compilerOptions": { 50 | // Compiler options... 51 | }, 52 | "include": [ 53 | "src/**/*.ts", 54 | "tests/**/*.ts" 55 | ], 56 | "exclude": [ 57 | "node_modules", 58 | "build" 59 | ] 60 | } 61 | ``` 62 | 63 | In this example, TypeScript includes files matching the `"include"` patterns but excludes files matching the `"exclude"` patterns. 64 | 65 | ### Using "files" Option: 66 | 67 | Alternatively, you can use the `"files"` option to explicitly list the files that should be included. This option overrides both `"include"` and `"exclude"`. Here's an example: 68 | 69 | ```json 70 | { 71 | "compilerOptions": { 72 | // Compiler options... 73 | }, 74 | "files": [ 75 | "src/main.ts", 76 | "src/utils/math.ts", 77 | "tests/test1.ts" 78 | ] 79 | } 80 | ``` 81 | 82 | In this example, TypeScript will only compile the files specified in the `"files"` array. 83 | 84 | Choose the approach that best fits your project's organization and requirements. The combination of `"include"`, `"exclude"`, and `"files"` options gives you flexibility in controlling which files are part of the TypeScript compilation process. -------------------------------------------------------------------------------- /TypeScript Compiler/Introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | The TypeScript compiler, often referred to as `tsc`, is a tool that converts TypeScript code (written in the TypeScript language) into equivalent JavaScript code. TypeScript is a superset of JavaScript that adds static typing and other features to the language. The TypeScript compiler is responsible for transpiling TypeScript code into a version of JavaScript that can run in any JavaScript environment. 4 | 5 | ## Table of Contents 6 | 7 | - [1. **TypeScript Source Code:**](#1-typescript-source-code) 8 | - [2. **.ts Files:**](#2-ts-files) 9 | - [3. **tsconfig.json:**](#3-tsconfigjson) 10 | - [4. **tsc Command:**](#4-tsc-command) 11 | - [5. **Compilation Process:**](#5-compilation-process) 12 | - [6. **Output Files:**](#6-output-files) 13 | - [7. **Running JavaScript Code:**](#7-running-javascript-code) 14 | - [8. **Continuous Compilation (watch mode):**](#8-continuous-compilation-watch-mode) 15 | 16 | 17 | ### 1. **TypeScript Source Code:** 18 | 19 | Developers write TypeScript code using the TypeScript language features, including static types, interfaces, classes, and other ECMAScript features. 20 | 21 | ### 2. **.ts Files:** 22 | 23 | TypeScript source code is typically stored in files with a `.ts` extension. These files contain the TypeScript code that needs to be compiled. 24 | 25 | ### 3. **tsconfig.json:** 26 | 27 | A `tsconfig.json` file may be present in the project to configure various compiler options. It includes settings such as the target ECMAScript version, module system, and whether to generate source maps. 28 | 29 | ### 4. **tsc Command:** 30 | 31 | Developers use the `tsc` command to invoke the TypeScript compiler. For example: 32 | 33 | ```bash 34 | tsc myfile.ts 35 | ``` 36 | 37 | This command tells the compiler to transpile the `myfile.ts` TypeScript file into JavaScript. 38 | 39 | ### 5. **Compilation Process:** 40 | 41 | The TypeScript compiler goes through several phases during compilation: 42 | 43 | - **Parsing:** The compiler reads the TypeScript source code and parses it into an Abstract Syntax Tree (AST). This AST represents the structure of the code. 44 | - **Type Checking:** TypeScript is a statically typed language, so the compiler performs type checking on the AST. It checks for type errors, ensuring that variables are used correctly and that type annotations match the actual usage. 45 | - **Intermediate Representation (IR):** The compiler generates an intermediate representation of the code. This representation includes information about types, interfaces, and other TypeScript-specific constructs. 46 | - **ECMAScript Code Generation:** Based on the intermediate representation, the compiler generates ECMAScript (JavaScript) code that corresponds to the TypeScript source code. This generated code adheres to the specified ECMAScript version and module system. 47 | 48 | ### 6. **Output Files:** 49 | 50 | The compiler creates one or more JavaScript files (`.js`) corresponding to the TypeScript source files. Additionally, it may generate declaration files (`.d.ts`) for type information and source map files (`.map`) for debugging. 51 | 52 | ### 7. **Running JavaScript Code:** 53 | 54 | The resulting JavaScript code can be executed in any JavaScript runtime, such as browsers, Node.js, or other JavaScript environments. 55 | 56 | ### 8. **Continuous Compilation (watch mode):** 57 | 58 | The TypeScript compiler provides a watch mode (`tsc --watch`), which monitors changes in the source files and automatically recompiles the code when modifications occur. This is useful during development to streamline the coding process. 59 | 60 | In summary, the TypeScript compiler takes TypeScript source code, performs type checking and other analyses, and then generates JavaScript code that can be executed in various JavaScript environments. The goal is to provide developers with the benefits of static typing while maintaining compatibility with existing JavaScript ecosystems. -------------------------------------------------------------------------------- /TypeScript Compiler/README.md: -------------------------------------------------------------------------------- 1 | # TypeScript Compiler 2 | 3 | ## Introduction 4 | 5 | Explore TypeScript Compiler's comprehensive guide to compilation, including managing multiple files, setting targets, and understanding Core Libs, for streamlined development. 6 | 7 | ## Table of Contents 8 | 9 | - [Introduction](./Introduction.md) 10 | - [Compiling the Entire Project / Multiple Files](./Compiling%20the%20Entire%20Project%20Multiple%20Files.md) 11 | - [Including & Excluding Files](./Including%20&%20Excluding%20Files.md) 12 | - [Setting a Compilation Target](TypeScript%20Compiler%203b9e3de17a3d4c32be8d308dcdf43c66/Setting%20a%20Compilation%20Target%2008f7836567d34ae9a0df116a6778f85d.md) 13 | - [Understanding TypeScript Core Libs](TypeScript%20Compiler%203b9e3de17a3d4c32be8d308dcdf43c66/Understanding%20TypeScript%20Core%20Libs%209714e61078e54c8d801ea4ca17e32906.md) -------------------------------------------------------------------------------- /TypeScript Compiler/Setting a Compilation Target.md: -------------------------------------------------------------------------------- 1 | # Setting a Compilation Target 2 | 3 | ## Introduction 4 | 5 | In TypeScript, you can set the compilation target to specify the ECMAScript version of the generated JavaScript code. The compilation target is defined using the `target` option in the `tsconfig.json` configuration file. This option ensures that the generated JavaScript code adheres to the specified ECMAScript version. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **Update tsconfig.json:**](#1-update-tsconfigjson) 10 | - [2. **Available Target Options:**](#2-available-target-options) 11 | - [3. **Example Configuration for ES6:**](#3-example-configuration-for-es6) 12 | - [4. **Consider Browser Compatibility:**](#4-consider-browser-compatibility) 13 | - [5. **Check TypeScript Version Compatibility:**](#5-check-typescript-version-compatibility) 14 | - [6. **Run the TypeScript Compiler:**](#6-run-the-typescript-compiler) 15 | 16 | 17 | ### 1. **Update tsconfig.json:** 18 | 19 | Open or create the `tsconfig.json` file in the root of your TypeScript project. Add or modify the `"compilerOptions"` section and set the `target` option to the desired ECMAScript version. 20 | 21 | For example, if you want to target ECMAScript 5 (ES5): 22 | 23 | ```json 24 | { 25 | "compilerOptions": { 26 | "target": "es5", 27 | "// other options...": "..." 28 | }, 29 | "// other settings...": "..." 30 | } 31 | ``` 32 | 33 | ### 2. **Available Target Options:** 34 | 35 | - **"es3"**: ECMAScript 3 36 | - **"es5"**: ECMAScript 5 37 | - **"es6" or "es2015"**: ECMAScript 2015 (ES6) 38 | - **"es2016"**: ECMAScript 2016 39 | - **"es2017"**: ECMAScript 2017 40 | - **"es2018"**: ECMAScript 2018 41 | - **"es2019"**: ECMAScript 2019 42 | - **"es2020"**: ECMAScript 2020 43 | - **"es2021"**: ECMAScript 2021 44 | - **"esnext"**: Latest ECMAScript version supported by your TypeScript version 45 | 46 | ### 3. **Example Configuration for ES6:** 47 | 48 | ```json 49 | { 50 | "compilerOptions": { 51 | "target": "es6", 52 | "// other options...": "..." 53 | }, 54 | "// other settings...": "..." 55 | } 56 | ``` 57 | 58 | In this example, the `target` is set to "es6," indicating that the generated JavaScript code should follow the ECMAScript 2015 (ES6) standard. 59 | 60 | ### 4. **Consider Browser Compatibility:** 61 | 62 | When setting the compilation target, consider the compatibility requirements of your target environment. For web development, you may want to target a version supported by the majority of your users' browsers. 63 | 64 | ### 5. **Check TypeScript Version Compatibility:** 65 | 66 | Ensure that your TypeScript version supports the selected compilation target. Newer ECMAScript versions may require a more recent TypeScript version for full support. 67 | 68 | ### 6. **Run the TypeScript Compiler:** 69 | 70 | After updating the `tsconfig.json` file, run the TypeScript compiler (`tsc`) to recompile your TypeScript code: 71 | 72 | ```bash 73 | tsc 74 | ``` 75 | 76 | This will generate JavaScript files in the specified output directory (`"outDir"`) with the specified ECMAScript version. 77 | 78 | Setting the compilation target is essential for ensuring compatibility with the intended runtime environment and taking advantage of the features available in the chosen ECMAScript version. -------------------------------------------------------------------------------- /TypeScript Compiler/Understanding TypeScript Core Libs.md: -------------------------------------------------------------------------------- 1 | # Understanding TypeScript Core Libs 2 | 3 | ## Introduction 4 | 5 | The core libraries (sometimes referred to as "lib files") are a set of declaration files that provide type information for the standard JavaScript runtime environment and commonly used JavaScript libraries. These declaration files enable TypeScript to understand the types and APIs available in these environments, allowing for improved type checking and autocompletion in your TypeScript code. 6 | 7 | ## Table of Contents 8 | 9 | - [1. **TypeScript Configuration (`tsconfig.json`):**](#1-typescript-configuration-tsconfigjson) 10 | - [2. **Common Core Libraries:**](#2-common-core-libraries) 11 | - [3. **Impact on Type Checking:**](#3-impact-on-type-checking) 12 | - [4. **Targeting Specific Environments:**](#4-targeting-specific-environments) 13 | - [5. **Customizing Core Libraries:**](#5-customizing-core-libraries) 14 | - [6. **Checking Available Libraries:**](#6-checking-available-libraries) 15 | - [7. **Use Case for `"scripthost"`:**](#7-use-case-for-scripthost) 16 | 17 | 18 | ### 1. **TypeScript Configuration (`tsconfig.json`):** 19 | 20 | The inclusion of core libraries is specified in the `tsconfig.json` file using the `"lib"` compiler option. The `"lib"` option allows you to include or exclude specific libraries. If you don't explicitly specify `"lib"`, TypeScript will include the default set of libraries based on the target ECMAScript version. 21 | 22 | Example of specifying core libraries in `tsconfig.json`: 23 | 24 | ```json 25 | { 26 | "compilerOptions": { 27 | "target": "es5", 28 | "lib": ["dom", "es2015", "scripthost"] 29 | // Other compiler options... 30 | } 31 | } 32 | ``` 33 | 34 | ### 2. **Common Core Libraries:** 35 | 36 | - **`"dom"`**: Includes the Document Object Model (DOM) types for web development. 37 | - **`"es5"`**: Adds types for ECMAScript 5 features. 38 | - **`"es6"` or `"es2015"`**: Adds types for ECMAScript 2015 (ES6) features. 39 | - **`"esnext"`**: Includes types for the latest ECMAScript features not yet standardized. 40 | 41 | ### 3. **Impact on Type Checking:** 42 | 43 | The core libraries influence type checking by providing type information for the functions, objects, and features available in the specified environments. They help TypeScript understand the types of variables, parameters, and return values, improving the accuracy of type checking. 44 | 45 | ### 4. **Targeting Specific Environments:** 46 | 47 | Depending on your project and deployment environment, you may choose specific core libraries to include. For example, if you are building a web application, including `"dom"` is essential for working with the DOM API. 48 | 49 | ### 5. **Customizing Core Libraries:** 50 | 51 | You can customize the set of core libraries based on your needs. Specifying `"lib": []` in `tsconfig.json` will exclude all default libraries, and you can selectively include only the ones you need. 52 | 53 | ```json 54 | { 55 | "compilerOptions": { 56 | "target": "es6", 57 | "lib": [] 58 | // Other compiler options... 59 | } 60 | } 61 | ``` 62 | 63 | ### 6. **Checking Available Libraries:** 64 | 65 | You can check the available core libraries for a specific TypeScript version in the TypeScript documentation or by consulting the TypeScript source code. The `lib` folder in the TypeScript GitHub repository contains the declaration files for core libraries. 66 | 67 | ### 7. **Use Case for `"scripthost"`:** 68 | 69 | The `"scripthost"` library is sometimes included to support scenarios where TypeScript code runs in non-browser environments (e.g., Node.js) that may lack certain browser-specific APIs. 70 | 71 | ```json 72 | { 73 | "compilerOptions": { 74 | "target": "es6", 75 | "lib": ["dom", "es2015", "scripthost"] 76 | // Other compiler options... 77 | } 78 | } 79 | ``` 80 | 81 | Understanding and configuring TypeScript core libraries are essential for ensuring that your TypeScript code aligns with the target runtime environment and that type checking is accurate and comprehensive. -------------------------------------------------------------------------------- /tscookbookcover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/muratdemirci/typescript-cookbook/4211e5c75cb919b2108ad35ef9faa8d793dbe995/tscookbookcover.png --------------------------------------------------------------------------------