From 90d1c9828b057b40523c310e9a67c8872315cb03 Mon Sep 17 00:00:00 2001 From: Priyavrata Mohan <91372958+priyavratamohan@users.noreply.github.com> Date: Mon, 10 Jun 2024 16:56:39 +0530 Subject: [PATCH 1/2] Upload TypeScript Files --- docs/javascript/basic-js.md | 2 +- docs/typescript/advanced-types-ts.md | 96 +++++++ docs/typescript/classes-ts.md | 246 ++++++++++++++++++ docs/typescript/control-flow-ts.md | 185 +++++++++++++ docs/typescript/functions-ts.md | 112 ++++++++ docs/typescript/generics-ts.md | 89 +++++++ docs/typescript/interfaces-ts.md | 124 +++++++++ docs/typescript/intro-ts.md | 4 +- docs/typescript/simple-types-ts.md | 76 ++++++ docs/typescript/special-types-ts.md | 96 +++++++ ...7-Letter-Combinations-of-a-Phone-Number.md | 7 +- 11 files changed, 1032 insertions(+), 5 deletions(-) create mode 100644 docs/typescript/advanced-types-ts.md create mode 100644 docs/typescript/classes-ts.md create mode 100644 docs/typescript/control-flow-ts.md create mode 100644 docs/typescript/functions-ts.md create mode 100644 docs/typescript/generics-ts.md create mode 100644 docs/typescript/interfaces-ts.md create mode 100644 docs/typescript/simple-types-ts.md create mode 100644 docs/typescript/special-types-ts.md diff --git a/docs/javascript/basic-js.md b/docs/javascript/basic-js.md index 474ad7f5a..ebc2183a0 100644 --- a/docs/javascript/basic-js.md +++ b/docs/javascript/basic-js.md @@ -115,4 +115,4 @@ The `document.getElementById().innerText` method is used to write into an HTML e :::info **Before moving to the next section, make sure you have a basic understanding of the above concepts.** You can use any of the above methods to display the output in JavaScript. -::: \ No newline at end of file +::: diff --git a/docs/typescript/advanced-types-ts.md b/docs/typescript/advanced-types-ts.md new file mode 100644 index 000000000..2e5492d0a --- /dev/null +++ b/docs/typescript/advanced-types-ts.md @@ -0,0 +1,96 @@ +--- +id: advanced-types-ts +title: Advanced Types in TypeScript +sidebar_label: Advanced Types in TypeScript +sidebar_position: 8 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Advanced Types in TypeScript +--- + +In this section, you'll delve into advanced TypeScript types, which enable you to express more complex relationships between data structures and provide additional tools for type safety and flexibility in your code. + +## 1. Intersection Types + +Intersection types allow you to combine multiple types into one, creating a type that possesses all the properties and methods of each constituent type. + +Example - + +``` +interface Dog { + bark(): void; +} + +interface Cat { + meow(): void; +} + +type Pet = Dog & Cat; + +class DogImpl implements Dog { + bark(): void { + console.log("Woof! Woof!"); + } +} + +class CatImpl implements Cat { + meow(): void { + console.log("Meow! Meow!"); + } +} + +function makePet(): Pet { + return new DogImpl() as Pet; +} + +let pet: Pet = makePet(); +pet.bark(); // Output: Woof! Woof! +pet.meow(); // Output: Error: Property 'meow' does not exist on type 'Pet'. +``` + +## 2. Type Guards + +Type guards are runtime checks that allow TypeScript to infer more specific types within certain code paths, enhancing type safety and enabling more precise type checking. + +Example - + +``` +function isNumber(x: any): x is number { + return typeof x === "number"; +} + +function processValue(value: string | number): void { + if (isNumber(value)) { + console.log(value * 2); + } else { + console.log(value.toUpperCase()); + } +} + +processValue(10); // Output: 20 +processValue("hello"); // Output: HELLO + +``` + +## 3. Type Casting + +Type casting allows you to assert the type of a value, informing TypeScript's type system of your intent and enabling you to perform operations that require a specific type. + +Example - + +``` +let someValue: any = "hello"; +let strLength: number = (someValue as string).length; +console.log(strLength); // Output: 5 +``` + +## 4. Type Assertions + +Type assertions provide a way to override TypeScript's type inference and explicitly specify the type of a variable, giving you more control over type checking and enabling you to work with external data sources or dynamic values. + +Example - + +``` +let someValue: any = "hello"; +let strLength: number = (someValue as string).length; +console.log(strLength); // Output: 5 +``` diff --git a/docs/typescript/classes-ts.md b/docs/typescript/classes-ts.md new file mode 100644 index 000000000..bb2dd15eb --- /dev/null +++ b/docs/typescript/classes-ts.md @@ -0,0 +1,246 @@ +--- +id: classes-ts +title: Classes and Inheritance in TypeScript +sidebar_label: Classes and Inheritance in TypeScript +sidebar_position: 6 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Classes and Inheritance Rules used in TypeScript +--- +Classes are a fundamental feature of object-oriented programming (OOP) that provide a blueprint for creating objects with predefined properties and methods. In TypeScript, classes offer a powerful way to structure your code, encapsulate data, and organize functionality in a modular and reusable manner. + +**Using classes in TypeScript allows you to:** + + ***1. Encapsulate Data:*** Classes allow you to encapsulate related data and behavior into a single unit, promoting code organization and maintainability. + + ***2. Define Blueprints for Objects:*** With classes, you can define blueprints or templates for creating objects with consistent structures and behaviors. + + ***3. Implement Inheritance:*** TypeScript supports inheritance, allowing classes to inherit properties and methods from parent classes, enabling code reuse and promoting the principle of DRY (Don't Repeat Yourself). + + ***4. Utilize Access Modifiers:*** TypeScript provides access modifiers such as public, private, and protected, which allow you to control the visibility and accessibility of class members, enhancing data encapsulation and security. + + ***5. Implement Abstraction:*** Abstract classes and methods enable you to define common behaviors and structures without providing a concrete implementation, fostering modular design and extensibility. + + ***6. Utilize Static Members:*** Static members belong to the class itself rather than to any specific instance, providing a convenient way to define utility functions or shared data. + +In this section, you will explore various class-related concepts such as classes, access modifiers, the readonly modifier, getters & setters, inheritance, static methods & properties, and abstract classes, and learn how to use them effectively in your TypeScript programs. + +## 1. Classes + +Classes are blueprints for creating objects with predefined properties and methods. They encapsulate data and behavior, providing a clear structure for your programs. + +Example: + +``` +class Person { + name: string; + age: number; + + constructor(name: string, age: number) { + this.name = name; + this.age = age; + } + + greet(): void { + console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); + } +} + +let person = new Person("Alice", 30); +person.greet(); // Output: Hello, my name is Alice and I am 30 years old. +``` + +## 2. Access Modifiers + + These modifiers control the visibility of class members, enhancing encapsulation and protecting data. + The three types of access possible in TypeScript are private, protected, and public access modifiers. + +Example: + +``` +class Employee { + public name: string; // accessible from anywhere + private salary: number; // accessible only within the class + protected department: string; // accessible within the class and subclasses + + constructor(name: string, salary: number, department: string) { + this.name = name; + this.salary = salary; + this.department = department; + } + + public getDetails(): void { + console.log(`${this.name} works in the ${this.department} department.`); + } + + private getSalary(): number { + return this.salary; + } +} + +class Manager extends Employee { + constructor(name: string, salary: number, department: string) { + super(name, salary, department); + } + + public getManagerDetails(): void { + console.log(`${this.name} is a manager in the ${this.department} department.`); + } +} + +let manager = new Manager("Bob", 80000, "HR"); +manager.getDetails(); // Output: Bob works in the HR department. +// manager.getSalary(); // Error: Property 'getSalary' is private and only accessible within class 'Employee'. +manager.getManagerDetails(); // Output: Bob is a manager in the HR department. +``` + +## 3. The readonly Modifier + +Use the readonly modifier to make class properties immutable. Once assigned, the value of readonly properties cannot be changed, ensuring that certain critical properties remain constant. + +Example: + +``` +class Car { + readonly make: string; + readonly model: string; + year: number; + + constructor(make: string, model: string, year: number) { + this.make = make; + this.model = model; + this.year = year; + } + + displayDetails(): void { + console.log(`${this.year} ${this.make} ${this.model}`); + } +} + +let car = new Car("Toyota", "Corolla", 2020); +car.displayDetails(); // Output: 2020 Toyota Corolla +car.year = 2021; +car.displayDetails(); // Output: 2021 Toyota Corolla +// car.make = "Honda"; // Error: Cannot assign to 'make' because it is a read-only property. +``` + +## 4. Getters & Setters + +Getters and Setters allow you to control the access of the class properties. They enable the encapsulation of data, providing controlled access and modification of properties. + +Example: + +``` +class Circle { + private _radius: number; + + constructor(radius: number) { + this._radius = radius; + } + + get radius(): number { + return this._radius; + } + + set radius(value: number) { + if (value <= 0) { + throw new Error("Radius must be positive."); + } + this._radius = value; + } + + getArea(): number { + return Math.PI * this._radius * this._radius; + } +} + +let circle = new Circle(5); +console.log(circle.radius); // Output: 5 +circle.radius = 10; +console.log(circle.getArea()); // Output: 314.159... +// circle.radius = -5; // Error: Radius must be positive. +``` + +## 5. Inheritance + +Learn how to use inheritance to reuse the functionality of another class. Inheritance allows you to create a new class based on an existing class, extending its properties and methods. + +Example: + +``` +class Animal { + name: string; + + constructor(name: string) { + this.name = name; + } + + move(distance: number = 0): void { + console.log(`${this.name} moved ${distance} meters.`); + } +} + +class Dog extends Animal { + bark(): void { + console.log("Woof! Woof!"); + } +} + +let dog = new Dog("Rex"); +dog.bark(); // Output: Woof! Woof! +dog.move(10); // Output: Rex moved 10 meters. +``` + +## 6. Static Methods & Properties + +Define static methods and properties shared by all instances of a class. Static members belong to the class itself rather than to any specific instance, making them useful for utility functions or shared data. + +Example: + +``` +class MathUtil { + static PI: number = 3.14; + + static calculateCircumference(radius: number): number { + return 2 * MathUtil.PI * radius; + } +} + +console.log(MathUtil.PI); // Output: 3.14 +console.log(MathUtil.calculateCircumference(10)); // Output: 62.8 +``` + +## 7. Abstract Classes + +Explain the abstract classes that define some common behaviors. Abstract classes cannot be instantiated directly and are meant to be extended by other classes, providing a base structure and forcing implementation of specific methods. + +Example: + +``` +abstract class Shape { + abstract getArea(): number; + + display(): void { + console.log(`The area is ${this.getArea()}`); + } +} + +class Rectangle extends Shape { + width: number; + height: number; + + constructor(width: number, height: number) { + super(); + this.width = width; + this.height = height; + } + + getArea(): number { + return this.width * this.height; + } +} + +let rectangle = new Rectangle(5, 10); +rectangle.display(); // Output: The area is 50 +``` + +These concepts and examples illustrate how to effectively use classes and their advanced features in TypeScript, enhancing your ability to write robust and maintainable object-oriented code. diff --git a/docs/typescript/control-flow-ts.md b/docs/typescript/control-flow-ts.md new file mode 100644 index 000000000..411a3dc49 --- /dev/null +++ b/docs/typescript/control-flow-ts.md @@ -0,0 +1,185 @@ +--- +id: control-flow-ts +title: Control Flow Statements in TypeScript +sidebar_label: Control Flow Statements in TypeScript +sidebar_position: 4 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Control Flow Statements used in TypeScript +--- + +Control flow statements are essential constructs that allow you to dictate the order in which statements are executed in your TypeScript programs. These statements enable you to make decisions, repeat actions, and handle exceptions, thereby creating more dynamic and responsive applications. + +Below, we explore the various control flow statements available in TypeScript, complete with descriptions and examples to illustrate their use. + +You will explore various control flow statements such as if...else, switch, for, for...of, for...in, while, do...while, break, continue, try...catch...finally, and throw, and learn how to use them effectively in your TypeScript programs. + +## 1. if...else + +The if...else statement is used to execute a block of code based on a condition. + +Example: + +``` +let age: number = 25; +if (age >= 18) { + console.log("Adult"); +} else { + console.log("Minor"); +} +``` + +## 2. switch + +The switch statement is used to perform different actions based on different conditions. + +Example: + +``` +typescript + +let fruit: string = "apple"; +switch (fruit) { + case "apple": + console.log("Apple"); + break; + case "banana": + console.log("Banana"); + break; + default: + console.log("Unknown fruit"); +} +``` + +## 3. for + +The for loop is used to execute a block of code a specified number of times. + +Example: + +``` +for (let i = 0; i < 5; i++) { + console.log(i); +} +``` + +## 4. for...of + +The for...of loop is used to iterate over the values of an iterable object (like an array). + +Example: + +``` +let numbers: number[] = [1, 2, 3, 4]; +for (let num of numbers) { + console.log(num); +} +``` + +## 5. for...in + +The for...in loop is used to iterate over the keys of an object. + +Example: + +``` +let person: { name: string, age: number } = { name: "Alice", age: 25 }; +for (let key in person) { + console.log(key + ": " + person[key]); +} +``` + +## 6. while + +The while loop is used to execute a block of code as long as a specified condition is true. + +Example: + +``` +let count: number = 0; +while (count < 5) { + console.log(count); + count++; +} +``` + +## 7. do...while + +The do...while loop is similar to the while loop, but it will execute the block of code at least once before checking the condition. + +Example: + +``` +let count: number = 0; +do { + console.log(count); + count++; +} while (count < 5); +``` + +## 8. break + +The break statement is used to exit a loop or a switch statement. + +Example: + +``` +for (let i = 0; i < 5; i++) { + if (i === 3) { + break; + } + console.log(i); +} +``` + +## 9. continue + +The continue statement is used to skip the current iteration of a loop and continue with the next one. + +Example: + +``` +for (let i = 0; i < 5; i++) { + if (i === 3) { + continue; + } + console.log(i); +} +``` + +## 10. try...catch...finally + +The try...catch...finally statement is used to handle exceptions and execute code regardless of whether an exception was thrown. + +Example: + +``` +try { + let result: number = 10 / 0; + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); +} finally { + console.log("This will always execute"); +} +``` + +## 11. throw + +The throw statement is used to create a custom error. + +Example: + +``` +function divide(a: number, b: number): number { + if (b === 0) { + throw new Error("Division by zero"); + } + return a / b; +} + +try { + console.log(divide(10, 0)); +} catch (error) { + console.log("An error occurred: " + error.message); +} +``` diff --git a/docs/typescript/functions-ts.md b/docs/typescript/functions-ts.md new file mode 100644 index 000000000..10d5013c4 --- /dev/null +++ b/docs/typescript/functions-ts.md @@ -0,0 +1,112 @@ +--- +id: funtions-ts +title: Functions in TypeScript +sidebar_label: Functions in TypeScript +sidebar_position: 5 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Functions used in TypeScript +--- + +Now that you're equipped with a detailed description of Simple Datatypes, Special Datatypes, Control Statements and other conecpts, it's time to put them to good use! + +In this section, you will explore various function-related concepts such as functions, function types, optional parameters, default parameters, rest parameters, and function overloadings, and learn how to use them effectively in your TypeScript programs. + +## 1. Functions + + Type annotations in functions ensure that the arguments passed to the function and the value it returns are of the expected type. + +Example: + +``` +function add(a: number, b: number): number { + return a + b; +} + +let result = add(5, 3); // 8 +console.log(result); // Output: 8 +``` + +## 2. Function Types + +Function types specify the parameter types and return type, allowing you to ensure consistency when assigning functions to variables. + +Example: + +``` +let myFunction: (a: number, b: number) => number; + +myFunction = function(x: number, y: number): number { + return x + y; +} + +console.log(myFunction(2, 3)); // Output: 5 +``` + +## 3. Optional Parameters + +Optional parameters allow you to call a function without passing some arguments, using the ? syntax. + +Example: + +``` +function greet(name: string, greeting?: string): string { + return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`; +} + +console.log(greet("Alice")); // Output: Hello, Alice! +console.log(greet("Alice", "Good morning")); // Output: Good morning, Alice! +``` + +## 4. Default Parameters + +Default parameters allow you to specify default values for function parameters, which will be used if no value is provided. + +Example: + +``` +function multiply(a: number, b: number = 1): number { + return a * b; +} + +console.log(multiply(5)); // Output: 5 +console.log(multiply(5, 2)); // Output: 10 +``` + +## 5. Rest Parameters + +Use the rest parameters to handle an infinite number of arguments of a function. Rest parameters allow you to represent an indefinite number of arguments as an array. + +Example: + +``` +function sum(...numbers: number[]): number { + return numbers.reduce((total, num) => total + num, 0); +} + +console.log(sum(1, 2, 3)); // Output: 6 +console.log(sum(1, 2, 3, 4, 5)); // Output: 15 +``` + +## 6. Function Overloadings + +Function overloadings allow you to define multiple function signatures for the same function, enabling it to handle different argument types and counts. + +Example: + +``` +function combine(a: string, b: string): string; +function combine(a: number, b: number): number; +function combine(a: any, b: any): any { + if (typeof a === "string" && typeof b === "string") { + return a + b; + } + if (typeof a === "number" && typeof b === "number") { + return a + b; + } +} + +console.log(combine("Hello, ", "world!")); // Output: Hello, world! +console.log(combine(10, 20)); // Output: 30 +``` + +These concepts and examples illustrate how to effectively use functions and their advanced features in TypeScript, enhancing your ability to write robust and type-safe code. diff --git a/docs/typescript/generics-ts.md b/docs/typescript/generics-ts.md new file mode 100644 index 000000000..a7d9bf3d2 --- /dev/null +++ b/docs/typescript/generics-ts.md @@ -0,0 +1,89 @@ +--- +id: generics-ts +title: Generics in TypeScript +sidebar_label: Generics in TypeScript +sidebar_position: 9 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Generics in TypeScript +--- + +In Computer Science, generics refer to a programming language feature that allows for the creation of functions, classes, and data structures that can operate on multiple data types. + +The concept of generics is rooted in the idea of parameterizing types or algorithms over other types. This means that you can define a function, class, or data structure with placeholders for the types it works with, rather than specifying concrete types. + +## 1. Introduction to TypeScript Generics + +Discover how to use TypeScript generics to develop generic functions. Generics enable you to write functions that can work with a variety of data types, providing type safety and code reusability. + +Example - + +``` +// Generic function to echo an argument +function echo(arg: T): T { + return arg; +} + +let result1: string = echo("Hello, TypeScript Generics!"); +let result2: number = echo(42); + +console.log(result1); // Output: Hello, TypeScript Generics! +console.log(result2); // Output: 42 +``` + +## 2. Generic Constraints + +Generic constraints allow you to restrict the types that can be used with generics, providing additional type safety and enabling more precise type inference. + +Example - + +``` +// Generic function to log the length of an array +function logLength(arr: T): void { + console.log(`Length of array: ${arr.length}`); +} + +logLength([1, 2, 3]); // Output: Length of array: 3 +logLength("typescript"); // Output: Length of array: 10 +// logLength(42); // Error: Argument of type '42' is not assignable to parameter of type '{ length: number; }' +``` + +## 3. Generic Classes + +Generic classes allow you to create classes that can work with different types of data, providing flexibility and code reusability. + +Example - + +``` +// Generic class for a pair of values +class Pair { + constructor(public first: T, public second: U) {} + + toString(): string { + return `(${this.first}, ${this.second})`; + } +} + +let pair1 = new Pair(1, "one"); +let pair2 = new Pair("yes", true); + +console.log(pair1.toString()); // Output: (1, one) +console.log(pair2.toString()); // Output: (yes, true) +``` + +## 4. Generic Interfaces + +Generic interfaces enable you to define interfaces with generic type parameters, allowing for the creation of flexible and reusable abstractions. + +Example - + +``` +interface Pair { + first: T; + second: U; +} + +let pair: Pair = { first: 1, second: "two" }; +console.log(pair); // Output: { first: 1, second: "two" } +``` + +These implementations demonstrate how to use TypeScript generics to create generic functions, add constraints to generic types, develop generic classes, and define generic interfaces, showcasing the flexibility and reusability provided by generics in TypeScript. diff --git a/docs/typescript/interfaces-ts.md b/docs/typescript/interfaces-ts.md new file mode 100644 index 000000000..bdd7055ea --- /dev/null +++ b/docs/typescript/interfaces-ts.md @@ -0,0 +1,124 @@ +--- +id: interfaces-ts +title: Interfaces in TypeScript +sidebar_label: Interfaces in TypeScript +sidebar_position: 7 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Interfaces and its implementation in TypeScript +--- + +In Computer Science, interfaces refer to a key concept used in various programming paradigms, particularly in object-oriented programming (OOP). An interface defines a contract for a set of operations or functionalities that a class or object must adhere to. It serves as a blueprint for defining the structure and behavior of objects without providing any concrete implementation details. + +**Key Aspects of Interfaces:** + +***1. Abstraction:*** Interfaces abstract away the implementation details of a class, focusing solely on the functionalities it must provide. This allows for clear separation of concerns and promotes modular design. + +***2. Contractual Obligation:*** Classes that implement an interface are obligated to implement all the methods and properties specified by the interface. This ensures consistency and interoperability within the codebase. + +***3. Polymorphism:*** Interfaces enable polymorphic behavior, where objects of different classes that implement the same interface can be treated uniformly, allowing for flexibility and extensibility in software design. + +***4. Multiple Inheritance:*** In languages that support it, interfaces provide a way to achieve multiple inheritance by allowing a class to implement multiple interfaces. This allows for the composition of different behaviors from multiple sources. + +***5. Design by Contract:*** Interfaces facilitate the design by contract principle, where the interactions between components are defined through preconditions, postconditions, and invariants specified by interfaces, promoting robust and reliable software systems. + +***6. Loose Coupling:*** By programming to interfaces rather than concrete implementations, code becomes less coupled to specific classes, making it easier to refactor and maintain. + +In this section, you'll delve into interfaces, a key feature of TypeScript, and explore how they facilitate creating contracts within your codebase. You'll also learn about extending interfaces to compose new ones and understand the distinctions between interfaces and abstract classes. + +## 1. Interfaces + +Interfaces in TypeScript define the structure of objects and specify the types of their properties and methods, ensuring consistency and interoperability. + +``` +interface Shape { + name: string; + area(): number; +} + +class Circle implements Shape { + name: string; + radius: number; + + constructor(name: string, radius: number) { + this.name = name; + this.radius = radius; + } + + area(): number { + return Math.PI * this.radius ** 2; + } +} + +let circle: Shape = new Circle("Circle", 5); +console.log(circle.area()); // Output: 78.54 +``` + +## 2. Extending Interfaces + +Extending interfaces allows you to inherit the properties and methods of one interface into another, enabling you to build more complex and reusable interfaces. + +``` +interface Animal { + name: string; + sound(): string; +} + +interface Dog extends Animal { + breed: string; +} + +class Labrador implements Dog { + name: string; + breed: string; + + constructor(name: string, breed: string) { + this.name = name; + this.breed = breed; + } + + sound(): string { + return "Woof! Woof!"; + } +} + +let dog: Dog = new Labrador("Max", "Labrador"); +console.log(dog.sound()); // Output: Woof! Woof! +``` + +## 3. Interfaces vs. Abstract Classes + +While both interfaces and abstract classes enable you to define blueprints for objects, they have distinct purposes and characteristics. Understanding these differences is crucial for choosing the appropriate approach for your design needs. + +``` +interface Vehicle { + name: string; + start(): void; + stop(): void; +} + +abstract class Car implements Vehicle { + name: string; + + constructor(name: string) { + this.name = name; + } + + start(): void { + console.log(`${this.name} started.`); + } + + abstract stop(): void; +} + +class Sedan extends Car { + stop(): void { + console.log(`${this.name} stopped.`); + } +} + +let sedan: Vehicle = new Sedan("Toyota Camry"); +sedan.start(); // Output: Toyota Camry started. +sedan.stop(); // Output: Toyota Camry stopped. +``` + +These examples demonstrate how interfaces and abstract classes are implemented and utilized in TypeScript, showcasing their versatility and usefulness in defining contracts and structuring your codebase. diff --git a/docs/typescript/intro-ts.md b/docs/typescript/intro-ts.md index 9b22f379f..ae7c5c0b7 100644 --- a/docs/typescript/intro-ts.md +++ b/docs/typescript/intro-ts.md @@ -9,6 +9,8 @@ description: TypeScript is a superset of JavaScript that adds static types to th In this tutorial, we will learn about TypeScript, a superset of JavaScript that adds static types to the language. TypeScript is a powerful tool that helps developers write more robust and maintainable code. It provides features like type checking, interfaces, classes, and modules that make it easier to build large-scale applications. +You’ve probably already heard that TypeScript is a “flavor” or “variant” of JavaScript. The relationship between TypeScript (TS) and JavaScript (JS) is rather unique among modern programming languages, so learning more about this relationship will help you understand how TypeScript adds to JavaScript. + ## What is TypeScript? TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It is designed for the development of large applications and transpiles to JavaScript for execution in the browser or on the server. TypeScript adds optional static types to JavaScript, which can help catch errors at compile time and improve code quality. @@ -81,4 +83,4 @@ This will output `Hello, World!` to the console. ## Conclusion -In this tutorial, we learned about TypeScript, a statically typed superset of JavaScript that adds static types to the language. TypeScript provides several benefits like static typing, improved code quality, modern features, and tooling support that make it a powerful tool for building large-scale applications. We also saw how to get started with TypeScript by installing the TypeScript compiler and writing a simple TypeScript program. \ No newline at end of file +In this tutorial, we learned about TypeScript, a statically typed superset of JavaScript that adds static types to the language. TypeScript provides several benefits like static typing, improved code quality, modern features, and tooling support that make it a powerful tool for building large-scale applications. We also saw how to get started with TypeScript by installing the TypeScript compiler and writing a simple TypeScript program. diff --git a/docs/typescript/simple-types-ts.md b/docs/typescript/simple-types-ts.md new file mode 100644 index 000000000..180d8006c --- /dev/null +++ b/docs/typescript/simple-types-ts.md @@ -0,0 +1,76 @@ +--- +id: simple-types-ts +title: Simple Datatypes in TypeScript +sidebar_label: Simple Datatypes in TypeScript +sidebar_position: 2 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Simple Datatypes used in TypeScript +--- + +In this tutorial, you will learn about the basic concepts of data types in TypeScript. We know that TypeScript is a superset of JavaScript that adds static typing, making it easier to catch errors during development. + +In this section, we focus more on generic datatypes that transcend into TypeScript from JavaScript, which will be helpful to know once we move forward to TypeScript Special Datatypes. + +You will explore various data types such as **string, number, boolean, array, tuple, enum, any, void, null, and undefined,** and learn how to use them effectively in your TypeScript programs. + +## List of Datatypes common in both JavaScript and TypeScript - + +## 1. Number + +The 'Number' datatype is used to represent both integer and floating-point numbers. Also includes special values like 'Infinity', '-Infinity', and 'NaN'. + +Example: `let age: number = 25;` + +## 2. String + +The 'String' datatype is used to represent a sequence of characters. + +Example: `let name: string = "Alice";` + +## 3. Boolean + +The 'Boolean' datatype is used to represent a logical entity with two values: true or false. + +Example: `let isActive: boolean = true;` + +## 4. Object + +The 'Object' datatype is used to represent a collection of key-value pairs. + +Example: `let person: object = { name: "Alice", age: 25 };` + +## 5. Array + +The 'Array' datatype is used to represent a list of values. + +Example: `let numbers: number[] = [1, 2, 3, 4];` + +## 6. Function + +The 'Function' datatype is used to represent a callable piece of code. + +Example: `let greet: Function = function(name: string) { return "Hello " + name; };` + +## 7. Undefined + +The 'Undefined' datatype is used to represent a variable that has been declared but not assigned a value. + +Example: `let notAssigned: undefined;` + +## 8. Null + +The 'Null' datatype is used to represent the intentional absence of any object value. + +Example: `let empty: null = null;` + +## 9. Symbol + +The 'Symbol' datatype (introduced in ES6) is used to represent a unique and immutable primitive value. + +Example: `let sym: symbol = Symbol("unique");` + +## 10. BigInt + +The 'BigInt' datatype (introduced in ES2020) is used to represent an integer with arbitrary precision. + +Example: `let bigNumber: bigint = 9007199254740991n;` diff --git a/docs/typescript/special-types-ts.md b/docs/typescript/special-types-ts.md new file mode 100644 index 000000000..ecf81854f --- /dev/null +++ b/docs/typescript/special-types-ts.md @@ -0,0 +1,96 @@ +--- +id: special-types-ts +title: Special Datatypes in TypeScript +sidebar_label: Special Datatypes in TypeScript +sidebar_position: 3 +tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide] +description: A Description of Special Datatypes used in TypeScript +--- +In this section, we focus more on the datatypes that are specific to TypeScript, which are the gateway for you to start properly delving into some TypeScript Coding. + +In the first module, we told you that TypeScript is a “flavor” or “variant” of JavaScript. These datatypes add up onto the datatypes we learnt in the previous module. + +You will explore various data types such as **tuple, enum, any, void and learn how to use them effectively in your TypeScript programs. + +## 1. Tuple + +The 'Tuple' datatype is used to represent an array with a fixed number of elements, each with a specific type. + +Example: `let tuple: [number, string] = [1, "Alice"];` + +## 2. Enum + +The 'Enum' datatype is used to define a set of named constants. + +Example: + +``` +typescript + +enum Color { Red, Green, Blue } +let c: Color = Color.Green; +``` + +## 3. Any + +The 'Any' datatype is used to represent any type, and is used to opt out of type-checking. + +Example: `let variable: any = "Could be anything";` + +## 4. Void + +The 'Void' datatype is used to represent the absence of any type, commonly used as the return type of functions that do not return a value. + +Example: `function log(message: string): void { console.log(message); }` + +## 5. Never + +The 'Never' datatype is used to represent the type of values that never occur, typically used for functions that always throw an error or never return. + +Example: `function error(message: string): never { throw new Error(message); }` + +## 6. Unknown + +The 'Unknown' datatype is used to represent a type-safe counterpart to any. + +Example: `let uncertain: unknown = 4;` + +## 7. Intersection Types + +The 'Intersection Types' datatype is used to combine multiple types into one. + +Example: `type Combined = { a: number } & { b: string };` + +## 8. Union Types + +The 'Union Types' datatype is used to represent a value that can be one of several types. + +Example: `let value: number | string = "hello";` + +## 9. Literal Types + +The 'Literal Types' datatype is used to represent specific values. + +Example: `let direction: "up" | "down" = "up";` + +## 10. Type Aliases + +The 'Type Aliases' datatype is used to provide a name for any type. + +Example: `type StringOrNumber = string | number;` + +## 11. Interfaces + +The 'Interfaces' datatype is used to describe the shape of an object. + +Example: + +``` +typescript + +interface Person { + name: string; + age: number; +} +let user: Person = { name: "Alice", age: 25 }; +``` diff --git a/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md b/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md index de07f5ca6..fd6fed234 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md +++ b/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md @@ -1,7 +1,7 @@ --- -id: Letter Combinations of a Phone Number +id: letter-combinations-of-a-phone-number title: Letter Combinations of a Phone Number (LeetCode) -sidebar_label: 0017-Letter-Combinations-of-a-Phone-Number +sidebar_label: 0017 Letter Combinations of a Phone Number tags: - Back Tracking - Mapping @@ -39,6 +39,7 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - **Output:** `["a","b","c"]` ### Constraints: + - `0 ≤ digits.length ≤ 4` - `0 ≤ digits.length ≤ 4digits[𝑖]` - `digits[i] is a digit in the range ['2', '9'].` @@ -313,4 +314,4 @@ Here's a step-by-step algorithm for generating all possible letter combinations - Call the backtracking function with the initial index set to 0 and an empty string as the initial combination. - Return the list of combinations. -This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. \ No newline at end of file +This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. From ed885e75f4357df8b459d8e51185497a4a2403fa Mon Sep 17 00:00:00 2001 From: Priyavrata Mohan <91372958+priyavratamohan@users.noreply.github.com> Date: Tue, 11 Jun 2024 12:34:24 +0530 Subject: [PATCH 2/2] Added tsx title='typescript' and made changes for best coding practices --- docs/typescript/advanced-types-ts.md | 8 +- docs/typescript/classes-ts.md | 264 +++++++++++++-------------- docs/typescript/control-flow-ts.md | 22 +-- docs/typescript/functions-ts.md | 12 +- docs/typescript/generics-ts.md | 8 +- docs/typescript/interfaces-ts.md | 6 +- docs/typescript/special-types-ts.md | 4 +- 7 files changed, 162 insertions(+), 162 deletions(-) diff --git a/docs/typescript/advanced-types-ts.md b/docs/typescript/advanced-types-ts.md index 2e5492d0a..e052db7ca 100644 --- a/docs/typescript/advanced-types-ts.md +++ b/docs/typescript/advanced-types-ts.md @@ -15,7 +15,7 @@ Intersection types allow you to combine multiple types into one, creating a type Example - -``` +```tsx title='typescript' interface Dog { bark(): void; } @@ -53,7 +53,7 @@ Type guards are runtime checks that allow TypeScript to infer more specific type Example - -``` +```tsx title='typescript' function isNumber(x: any): x is number { return typeof x === "number"; } @@ -77,7 +77,7 @@ Type casting allows you to assert the type of a value, informing TypeScript's ty Example - -``` +```tsx title='typescript' let someValue: any = "hello"; let strLength: number = (someValue as string).length; console.log(strLength); // Output: 5 @@ -89,7 +89,7 @@ Type assertions provide a way to override TypeScript's type inference and explic Example - -``` +```tsx title='typescript' let someValue: any = "hello"; let strLength: number = (someValue as string).length; console.log(strLength); // Output: 5 diff --git a/docs/typescript/classes-ts.md b/docs/typescript/classes-ts.md index bb2dd15eb..00f785d2e 100644 --- a/docs/typescript/classes-ts.md +++ b/docs/typescript/classes-ts.md @@ -30,24 +30,24 @@ Classes are blueprints for creating objects with predefined properties and metho Example: -``` -class Person { - name: string; - age: number; - - constructor(name: string, age: number) { - this.name = name; - this.age = age; - } + ```tsx title='typescript' + class Person { + name: string; + age: number; + + constructor(name: string, age: number) { + this.name = name; + this.age = age; + } - greet(): void { - console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); + greet(): void { + console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); + } } -} -let person = new Person("Alice", 30); -person.greet(); // Output: Hello, my name is Alice and I am 30 years old. -``` + let person = new Person("Alice", 30); + person.greet(); // Output: Hello, my name is Alice and I am 30 years old. + ``` ## 2. Access Modifiers @@ -56,42 +56,42 @@ person.greet(); // Output: Hello, my name is Alice and I am 30 years old. Example: -``` -class Employee { - public name: string; // accessible from anywhere - private salary: number; // accessible only within the class - protected department: string; // accessible within the class and subclasses + ```tsx title='typescript' + class Employee { + public name: string; // accessible from anywhere + private salary: number; // accessible only within the class + protected department: string; // accessible within the class and subclasses - constructor(name: string, salary: number, department: string) { - this.name = name; - this.salary = salary; - this.department = department; - } + constructor(name: string, salary: number, department: string) { + this.name = name; + this.salary = salary; + this.department = department; + } - public getDetails(): void { - console.log(`${this.name} works in the ${this.department} department.`); - } + public getDetails(): void { + console.log(`${this.name} works in the ${this.department} department.`); + } - private getSalary(): number { - return this.salary; + private getSalary(): number { + return this.salary; + } } -} -class Manager extends Employee { - constructor(name: string, salary: number, department: string) { - super(name, salary, department); - } + class Manager extends Employee { + constructor(name: string, salary: number, department: string) { + super(name, salary, department); + } - public getManagerDetails(): void { - console.log(`${this.name} is a manager in the ${this.department} department.`); + public getManagerDetails(): void { + console.log(`${this.name} is a manager in the ${this.department} department.`); + } } -} -let manager = new Manager("Bob", 80000, "HR"); -manager.getDetails(); // Output: Bob works in the HR department. -// manager.getSalary(); // Error: Property 'getSalary' is private and only accessible within class 'Employee'. -manager.getManagerDetails(); // Output: Bob is a manager in the HR department. -``` + let manager = new Manager("Bob", 80000, "HR"); + manager.getDetails(); // Output: Bob works in the HR department. + // manager.getSalary(); // Error: Property 'getSalary' is private and only accessible within class 'Employee'. + manager.getManagerDetails(); // Output: Bob is a manager in the HR department. + ``` ## 3. The readonly Modifier @@ -99,29 +99,29 @@ Use the readonly modifier to make class properties immutable. Once assigned, the Example: -``` -class Car { - readonly make: string; - readonly model: string; - year: number; + ```tsx title='typescript' + class Car { + readonly make: string; + readonly model: string; + year: number; - constructor(make: string, model: string, year: number) { - this.make = make; - this.model = model; - this.year = year; - } + constructor(make: string, model: string, year: number) { + this.make = make; + this.model = model; + this.year = year; + } - displayDetails(): void { - console.log(`${this.year} ${this.make} ${this.model}`); + displayDetails(): void { + console.log(`${this.year} ${this.make} ${this.model}`); + } } -} -let car = new Car("Toyota", "Corolla", 2020); -car.displayDetails(); // Output: 2020 Toyota Corolla -car.year = 2021; -car.displayDetails(); // Output: 2021 Toyota Corolla -// car.make = "Honda"; // Error: Cannot assign to 'make' because it is a read-only property. -``` + let car = new Car("Toyota", "Corolla", 2020); + car.displayDetails(); // Output: 2020 Toyota Corolla + car.year = 2021; + car.displayDetails(); // Output: 2021 Toyota Corolla + // car.make = "Honda"; // Error: Cannot assign to 'make' because it is a read-only property. + ``` ## 4. Getters & Setters @@ -129,36 +129,36 @@ Getters and Setters allow you to control the access of the class properties. The Example: -``` -class Circle { - private _radius: number; + ```tsx title='typescript' + class Circle { + private _radius: number; - constructor(radius: number) { - this._radius = radius; - } + constructor(radius: number) { + this._radius = radius; + } - get radius(): number { - return this._radius; - } + get radius(): number { + return this._radius; + } - set radius(value: number) { - if (value <= 0) { - throw new Error("Radius must be positive."); + set radius(value: number) { + if (value <= 0) { + throw new Error("Radius must be positive."); + } + this._radius = value; } - this._radius = value; - } - getArea(): number { - return Math.PI * this._radius * this._radius; + getArea(): number { + return Math.PI * this._radius * this._radius; + } } -} -let circle = new Circle(5); -console.log(circle.radius); // Output: 5 -circle.radius = 10; -console.log(circle.getArea()); // Output: 314.159... -// circle.radius = -5; // Error: Radius must be positive. -``` + let circle = new Circle(5); + console.log(circle.radius); // Output: 5 + circle.radius = 10; + console.log(circle.getArea()); // Output: 314.159... + // circle.radius = -5; // Error: Radius must be positive. + ``` ## 5. Inheritance @@ -166,29 +166,29 @@ Learn how to use inheritance to reuse the functionality of another class. Inheri Example: -``` -class Animal { - name: string; + ```tsx title='typescript' + class Animal { + name: string; - constructor(name: string) { - this.name = name; - } + constructor(name: string) { + this.name = name; + } - move(distance: number = 0): void { - console.log(`${this.name} moved ${distance} meters.`); + move(distance: number = 0): void { + console.log(`${this.name} moved ${distance} meters.`); + } } -} -class Dog extends Animal { - bark(): void { - console.log("Woof! Woof!"); + class Dog extends Animal { + bark(): void { + console.log("Woof! Woof!"); + } } -} -let dog = new Dog("Rex"); -dog.bark(); // Output: Woof! Woof! -dog.move(10); // Output: Rex moved 10 meters. -``` + let dog = new Dog("Rex"); + dog.bark(); // Output: Woof! Woof! + dog.move(10); // Output: Rex moved 10 meters. + ``` ## 6. Static Methods & Properties @@ -196,51 +196,51 @@ Define static methods and properties shared by all instances of a class. Static Example: -``` -class MathUtil { - static PI: number = 3.14; + ```tsx title='typescript' + class MathUtil { + static PI: number = 3.14; - static calculateCircumference(radius: number): number { - return 2 * MathUtil.PI * radius; + static calculateCircumference(radius: number): number { + return 2 * MathUtil.PI * radius; + } } -} -console.log(MathUtil.PI); // Output: 3.14 -console.log(MathUtil.calculateCircumference(10)); // Output: 62.8 -``` + console.log(MathUtil.PI); // Output: 3.14 + console.log(MathUtil.calculateCircumference(10)); // Output: 62.8 + ``` ## 7. Abstract Classes Explain the abstract classes that define some common behaviors. Abstract classes cannot be instantiated directly and are meant to be extended by other classes, providing a base structure and forcing implementation of specific methods. -Example: +Example - -``` -abstract class Shape { - abstract getArea(): number; + ```tsx title='typescript' + abstract class Shape { + abstract getArea(): number; - display(): void { - console.log(`The area is ${this.getArea()}`); + display(): void { + console.log(`The area is ${this.getArea()}`); + } } -} -class Rectangle extends Shape { - width: number; - height: number; + class Rectangle extends Shape { + width: number; + height: number; - constructor(width: number, height: number) { - super(); - this.width = width; - this.height = height; - } + constructor(width: number, height: number) { + super(); + this.width = width; + this.height = height; + } - getArea(): number { - return this.width * this.height; + getArea(): number { + return this.width * this.height; + } } -} -let rectangle = new Rectangle(5, 10); -rectangle.display(); // Output: The area is 50 -``` + let rectangle = new Rectangle(5, 10); + rectangle.display(); // Output: The area is 50 + ``` These concepts and examples illustrate how to effectively use classes and their advanced features in TypeScript, enhancing your ability to write robust and maintainable object-oriented code. diff --git a/docs/typescript/control-flow-ts.md b/docs/typescript/control-flow-ts.md index 411a3dc49..256be52db 100644 --- a/docs/typescript/control-flow-ts.md +++ b/docs/typescript/control-flow-ts.md @@ -19,7 +19,7 @@ The if...else statement is used to execute a block of code based on a condition. Example: -``` +```tsx title='typescript' let age: number = 25; if (age >= 18) { console.log("Adult"); @@ -34,7 +34,7 @@ The switch statement is used to perform different actions based on different con Example: -``` +```tsx title='typescript' typescript let fruit: string = "apple"; @@ -56,7 +56,7 @@ The for loop is used to execute a block of code a specified number of times. Example: -``` +```tsx title='typescript' for (let i = 0; i < 5; i++) { console.log(i); } @@ -68,7 +68,7 @@ The for...of loop is used to iterate over the values of an iterable object (like Example: -``` +```tsx title='typescript' let numbers: number[] = [1, 2, 3, 4]; for (let num of numbers) { console.log(num); @@ -81,7 +81,7 @@ The for...in loop is used to iterate over the keys of an object. Example: -``` +```tsx title='typescript' let person: { name: string, age: number } = { name: "Alice", age: 25 }; for (let key in person) { console.log(key + ": " + person[key]); @@ -94,7 +94,7 @@ The while loop is used to execute a block of code as long as a specified conditi Example: -``` +```tsx title='typescript' let count: number = 0; while (count < 5) { console.log(count); @@ -108,7 +108,7 @@ The do...while loop is similar to the while loop, but it will execute the block Example: -``` +```tsx title='typescript' let count: number = 0; do { console.log(count); @@ -122,7 +122,7 @@ The break statement is used to exit a loop or a switch statement. Example: -``` +```tsx title='typescript' for (let i = 0; i < 5; i++) { if (i === 3) { break; @@ -137,7 +137,7 @@ The continue statement is used to skip the current iteration of a loop and conti Example: -``` +```tsx title='typescript' for (let i = 0; i < 5; i++) { if (i === 3) { continue; @@ -152,7 +152,7 @@ The try...catch...finally statement is used to handle exceptions and execute cod Example: -``` +```tsx title='typescript' try { let result: number = 10 / 0; console.log(result); @@ -169,7 +169,7 @@ The throw statement is used to create a custom error. Example: -``` +```tsx title='typescript' function divide(a: number, b: number): number { if (b === 0) { throw new Error("Division by zero"); diff --git a/docs/typescript/functions-ts.md b/docs/typescript/functions-ts.md index 10d5013c4..bf1827c90 100644 --- a/docs/typescript/functions-ts.md +++ b/docs/typescript/functions-ts.md @@ -17,7 +17,7 @@ In this section, you will explore various function-related concepts such as func Example: -``` +```tsx title='typescript' function add(a: number, b: number): number { return a + b; } @@ -32,7 +32,7 @@ Function types specify the parameter types and return type, allowing you to ensu Example: -``` +```tsx title='typescript' let myFunction: (a: number, b: number) => number; myFunction = function(x: number, y: number): number { @@ -48,7 +48,7 @@ Optional parameters allow you to call a function without passing some arguments, Example: -``` +```tsx title='typescript' function greet(name: string, greeting?: string): string { return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`; } @@ -63,7 +63,7 @@ Default parameters allow you to specify default values for function parameters, Example: -``` +```tsx title='typescript' function multiply(a: number, b: number = 1): number { return a * b; } @@ -78,7 +78,7 @@ Use the rest parameters to handle an infinite number of arguments of a function. Example: -``` +```tsx title='typescript' function sum(...numbers: number[]): number { return numbers.reduce((total, num) => total + num, 0); } @@ -93,7 +93,7 @@ Function overloadings allow you to define multiple function signatures for the s Example: -``` +```tsx title='typescript' function combine(a: string, b: string): string; function combine(a: number, b: number): number; function combine(a: any, b: any): any { diff --git a/docs/typescript/generics-ts.md b/docs/typescript/generics-ts.md index a7d9bf3d2..264ef53e6 100644 --- a/docs/typescript/generics-ts.md +++ b/docs/typescript/generics-ts.md @@ -17,7 +17,7 @@ Discover how to use TypeScript generics to develop generic functions. Generics e Example - -``` +```tsx title='typescript' // Generic function to echo an argument function echo(arg: T): T { return arg; @@ -36,7 +36,7 @@ Generic constraints allow you to restrict the types that can be used with generi Example - -``` +```tsx title='typescript' // Generic function to log the length of an array function logLength(arr: T): void { console.log(`Length of array: ${arr.length}`); @@ -53,7 +53,7 @@ Generic classes allow you to create classes that can work with different types o Example - -``` +```tsx title='typescript' // Generic class for a pair of values class Pair { constructor(public first: T, public second: U) {} @@ -76,7 +76,7 @@ Generic interfaces enable you to define interfaces with generic type parameters, Example - -``` +```tsx title='typescript' interface Pair { first: T; second: U; diff --git a/docs/typescript/interfaces-ts.md b/docs/typescript/interfaces-ts.md index bdd7055ea..13f9e7eaa 100644 --- a/docs/typescript/interfaces-ts.md +++ b/docs/typescript/interfaces-ts.md @@ -29,7 +29,7 @@ In this section, you'll delve into interfaces, a key feature of TypeScript, and Interfaces in TypeScript define the structure of objects and specify the types of their properties and methods, ensuring consistency and interoperability. -``` +```tsx title='typescript' interface Shape { name: string; area(): number; @@ -57,7 +57,7 @@ console.log(circle.area()); // Output: 78.54 Extending interfaces allows you to inherit the properties and methods of one interface into another, enabling you to build more complex and reusable interfaces. -``` +```tsx title='typescript' interface Animal { name: string; sound(): string; @@ -89,7 +89,7 @@ console.log(dog.sound()); // Output: Woof! Woof! While both interfaces and abstract classes enable you to define blueprints for objects, they have distinct purposes and characteristics. Understanding these differences is crucial for choosing the appropriate approach for your design needs. -``` +```tsx title='typescript' interface Vehicle { name: string; start(): void; diff --git a/docs/typescript/special-types-ts.md b/docs/typescript/special-types-ts.md index ecf81854f..902d2965b 100644 --- a/docs/typescript/special-types-ts.md +++ b/docs/typescript/special-types-ts.md @@ -24,7 +24,7 @@ The 'Enum' datatype is used to define a set of named constants. Example: -``` +```tsx title='typescript' typescript enum Color { Red, Green, Blue } @@ -85,7 +85,7 @@ The 'Interfaces' datatype is used to describe the shape of an object. Example: -``` +```tsx title='typescript' typescript interface Person {