├── 01 hello typescript ├── 01-hello.js ├── 01-hello.ts ├── 02-variable.js ├── 02-variable.ts ├── 03-variable2.ts ├── intro.md └── variable.md ├── 02 functions ├── 01-function.ts ├── 02-function.js ├── 02-function.ts ├── 03-functions.ts ├── 04-function.ts ├── 05-arror-functions.ts └── functions.md ├── 03 objects ├── 01-object.ts ├── 02-object.ts ├── 03-object.ts └── objects.md ├── 04 arrays ├── 01-array.ts ├── 02-arrray.ts └── arrays.md ├── 05 tuple ├── 01-tuple.ts ├── 02-tuple.ts └── tuple.md ├── 06 enums ├── 01-enum.ts └── enum.md ├── 07 union ├── 01-union.ts └── union.md └── README.md /01 hello typescript/01-hello.js: -------------------------------------------------------------------------------- 1 | console.log("hello, new friend TYPESCRIPT ❤️🚀"); 2 | -------------------------------------------------------------------------------- /01 hello typescript/01-hello.ts: -------------------------------------------------------------------------------- 1 | console.log("hello, new friend TYPESCRIPT ❤️🚀"); 2 | -------------------------------------------------------------------------------- /01 hello typescript/02-variable.js: -------------------------------------------------------------------------------- 1 | var myName = "arvind"; 2 | //if i try to change the data type of myName, it will throw me an error 3 | myName = 7; 4 | /** 5 | * Type 'number' is not assignable to type 'string' 6 | let myName: string 7 | */ 8 | //typescript is smart, so i dont have explicitly mention the type 9 | var thisRepo = "hello typescript"; 10 | thisRepo = true; 11 | // Type 'boolean' is not assignable to type 'string'.ts(2322) 12 | // let thisRepo: string 13 | console.log(thisRepo); 14 | -------------------------------------------------------------------------------- /01 hello typescript/02-variable.ts: -------------------------------------------------------------------------------- 1 | let myName: string = "arvind"; 2 | 3 | //if i try to change the data type of myName, it will throw me an error 4 | 5 | myName = 7; 6 | 7 | /** 8 | * Type 'number' is not assignable to type 'string' 9 | let myName: string 10 | */ 11 | 12 | //typescript is smart, so i dont have explicitly mention the type 13 | 14 | let thisRepo = "hello typescript"; 15 | 16 | thisRepo = true; 17 | 18 | // Type 'boolean' is not assignable to type 'string'.ts(2322) 19 | // let thisRepo: string 20 | -------------------------------------------------------------------------------- /01 hello typescript/03-variable2.ts: -------------------------------------------------------------------------------- 1 | let num = 7; 2 | num.toString(); 3 | //num.toUpperCase -> error because toUpperCase function is available for number 4 | 5 | let nameOfCustomer = "arvind pandit"; 6 | nameOfCustomer.toUpperCase(); 7 | console.log(nameOfCustomer); 8 | -------------------------------------------------------------------------------- /01 hello typescript/intro.md: -------------------------------------------------------------------------------- 1 | # The History of TypeScript and Its Advantages and Disadvantages 2 | 3 | ## Introduction 4 | 5 | TypeScript is a popular programming language developed and maintained by Microsoft. It was first released in October 2012 and has since gained significant traction in the web development community. TypeScript builds upon JavaScript by introducing static typing, which brings several advantages and also comes with a few drawbacks. This README aims to provide an overview of TypeScript's history, the reasons behind its creation, and the benefits it offers over JavaScript, as well as its limitations. 6 | 7 | ## History of TypeScript 8 | 9 | TypeScript was conceptualized and developed by Anders Hejlsberg, the creator of C#, and his team at Microsoft. It was officially announced in October 2012 and released as an open-source project. The language was designed to address some of the challenges and limitations of JavaScript in building large-scale applications. TypeScript takes advantage of ECMAScript standards and introduces optional static typing, interfaces, classes, and other features that help developers write more maintainable and scalable code. 10 | 11 | ## Reasons for Creating TypeScript 12 | 13 | The creation of TypeScript was driven by several factors: 14 | 15 | 1. **Type Safety**: JavaScript is a dynamically typed language, which means that type-related errors are only discovered at runtime. TypeScript introduces static typing, allowing developers to catch type-related errors during development, leading to more robust and reliable code. 16 | 17 | 2. **Large-Scale Application Development**: JavaScript lacks certain features found in traditional object-oriented programming languages, making it challenging to manage complex codebases. TypeScript brings classes, interfaces, and other constructs that facilitate building large-scale applications. 18 | 19 | 3. **Tooling and IDE Support**: Static typing in TypeScript enables better tooling and IDE support. Code editors can offer improved auto-completion, refactoring capabilities, and error checking, enhancing developer productivity. 20 | 21 | 4. **Compatibility with ECMAScript**: TypeScript is designed to be a superset of ECMAScript, so existing JavaScript code can be gradually migrated to TypeScript without major refactoring. 22 | 23 | ## Advantages of TypeScript over JavaScript 24 | 25 | 1. **Static Typing**: TypeScript allows developers to specify types for variables, function parameters, and return values. This catches type-related errors early in the development process, leading to more reliable code. 26 | 27 | 2. **Enhanced IDE Support**: IDEs can provide better code intelligence, navigation, and refactoring tools due to TypeScript's type annotations. 28 | 29 | 3. **Improved Code Readability**: Type annotations serve as documentation, making the code more readable and understandable, especially in large codebases. 30 | 31 | 4. **Code Maintainability**: The use of classes, interfaces, and type declarations leads to more structured and maintainable code, particularly in large projects. 32 | 33 | 5. **Compatibility with JavaScript**: Existing JavaScript code can be gradually converted to TypeScript, allowing developers to adopt TypeScript incrementally. 34 | 35 | 6. **Strong Community and Tooling**: TypeScript has a large and active community, with excellent support from various tools, libraries, and frameworks. 36 | 37 | ## Disadvantages of TypeScript 38 | 39 | 1. **Learning Curve**: Developers familiar with JavaScript may need some time to get used to TypeScript's type system and features. 40 | 41 | 2. **Build Process**: Introducing TypeScript into a project requires an additional build step to transpile TypeScript code to JavaScript. 42 | 43 | 3. **Strictness**: While type safety is beneficial, TypeScript's strictness can sometimes feel restrictive, especially for prototyping or small projects. 44 | 45 | 4. **Compatibility with External Libraries**: Not all JavaScript libraries have TypeScript type definitions, which may require developers to write their own or rely on less type-safe approaches. 46 | 47 | ## Conclusion 48 | 49 | TypeScript was created to address the challenges of building large-scale applications in JavaScript. By introducing static typing and other language features, TypeScript offers several advantages over JavaScript, including enhanced code reliability, maintainability, and tooling support. However, it also comes with a learning curve and build complexities. Ultimately, the decision to use TypeScript depends on the specific requirements and goals of a project, as well as the familiarity and preferences of the development team. 50 | -------------------------------------------------------------------------------- /01 hello typescript/variable.md: -------------------------------------------------------------------------------- 1 | # TypeScript Basics and Types of Variables 2 | 3 | This readme contains code snippets and explanations for TypeScript basics and the different types of variables in TypeScript. TypeScript is a strongly typed superset of JavaScript that adds optional static typing to the language. It provides developers with better tooling, enhanced code readability, and improved maintainability, especially in large codebases. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction to TypeScript](#introduction-to-typescript) 8 | 2. [TypeScript Variables](#typescript-variables) 9 | - [let and const](#let-and-const) 10 | - [Primitive Types](#primitive-types) 11 | - [Arrays](#arrays) 12 | - [Objects](#objects) 13 | 14 | ## Introduction to TypeScript 15 | 16 | TypeScript is a programming language developed by Microsoft that builds on top of JavaScript by adding static typing features. This means that TypeScript allows developers to specify the type of variables, function parameters, and return values, which enables early detection of potential errors and improved code understanding. 17 | 18 | Key benefits of using TypeScript include: 19 | 20 | - **Type Safety**: TypeScript helps catch type-related errors during development, reducing runtime issues. 21 | - **Enhanced IDE Support**: With explicit type declarations, IDEs can provide better code completion and navigation. 22 | - **Code Maintainability**: The added type information makes codebases easier to maintain, especially in larger projects. 23 | - **Better Collaboration**: TypeScript's type annotations serve as a form of documentation, aiding team collaboration. 24 | 25 | ## TypeScript Variables 26 | 27 | In TypeScript, variables can be declared using `let`, `const`, or `var`. The type of the variable can be explicitly specified or inferred by the TypeScript compiler. 28 | 29 | ### let and const 30 | 31 | ```typescript 32 | let variable1: string = "Hello"; 33 | const variable2: number = 42; 34 | ``` 35 | 36 | - `let` is used for mutable variables whose values can be changed. 37 | - `const` is used for immutable variables, and once assigned, their values cannot be changed. 38 | 39 | ### Primitive Types 40 | 41 | TypeScript supports all the primitive types from JavaScript, and additional types can be specified explicitly. 42 | 43 | ```typescript 44 | let name: string = "John Doe"; 45 | let age: number = 30; 46 | let isStudent: boolean = true; 47 | let score: null = null; 48 | let description: undefined = undefined; 49 | let someValue: any = "I can be any type!"; 50 | ``` 51 | 52 | - `string`: Represents textual data. 53 | - `number`: Represents numeric values, both integers and floating-point numbers. 54 | - `boolean`: Represents true or false values. 55 | - `null` and `undefined`: Represent the absence of a value. 56 | - `any`: Represents a dynamic type that can hold any value. 57 | 58 | ### Arrays 59 | 60 | Arrays in TypeScript can be strongly typed by specifying the type of their elements. 61 | 62 | ```typescript 63 | let fruits: string[] = ["apple", "banana", "orange"]; 64 | let numbers: number[] = [1, 2, 3, 4, 5]; 65 | ``` 66 | 67 | ### Objects 68 | 69 | Object types allow us to define the shape of an object, specifying the type of each property. 70 | 71 | ```typescript 72 | type Person = { 73 | name: string; 74 | age: number; 75 | isStudent: boolean; 76 | }; 77 | 78 | let person: Person = { 79 | name: "Alice", 80 | age: 25, 81 | isStudent: true, 82 | }; 83 | ``` 84 | 85 | In this example, the `Person` type is defined with three properties: `name`, `age`, and `isStudent`. 86 | 87 | These are some of the basic concepts and types of variables in TypeScript. By leveraging TypeScript's type system, you can write more robust and maintainable code, catching errors early in the development process and improving collaboration within your team. 88 | 89 | Remember to install TypeScript via npm and use the TypeScript compiler (`tsc`) to transpile TypeScript code into JavaScript that can be executed in the browser or Node.js environment. 90 | 91 | For more advanced TypeScript concepts and features, please refer to the [official TypeScript documentation ](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) 92 | -------------------------------------------------------------------------------- /02 functions/01-function.ts: -------------------------------------------------------------------------------- 1 | function printName(name: string) { 2 | console.log(name); 3 | } 4 | 5 | printName("arvind"); 6 | 7 | //printName(7); 8 | //Argument of type 'number' is not assignable to parameter of type 'string'. 9 | -------------------------------------------------------------------------------- /02 functions/02-function.js: -------------------------------------------------------------------------------- 1 | function printName(name) { 2 | return name + " pandit"; 3 | } 4 | let myName = printName("arvind"); 5 | console.log(myName); 6 | -------------------------------------------------------------------------------- /02 functions/02-function.ts: -------------------------------------------------------------------------------- 1 | function printName(name: string): string { 2 | return name + " pandit"; 3 | } 4 | 5 | printName("arvind"); 6 | -------------------------------------------------------------------------------- /02 functions/03-functions.ts: -------------------------------------------------------------------------------- 1 | function lastName(): string { 2 | return " Pandit"; 3 | // return 7; 4 | } 5 | 6 | function firstName(name: string): string { 7 | return name + lastName(); 8 | } 9 | 10 | let myName = firstName("Arvind"); 11 | 12 | console.log(myName); 13 | -------------------------------------------------------------------------------- /02 functions/04-function.ts: -------------------------------------------------------------------------------- 1 | // default values in functions 2 | 3 | function studentInfo( 4 | studentName: string, 5 | studentId: number, 6 | studentClass: number = 12 7 | ): void { 8 | console.log(studentName, studentId, studentClass); 9 | } 10 | 11 | studentInfo("arvind", 1); 12 | -------------------------------------------------------------------------------- /02 functions/05-arror-functions.ts: -------------------------------------------------------------------------------- 1 | const divideByTen = (num: number): number => { 2 | return num / 10; 3 | }; 4 | 5 | divideByTen(1200); 6 | -------------------------------------------------------------------------------- /02 functions/functions.md: -------------------------------------------------------------------------------- 1 | # Functions in TypeScript 2 | 3 | This readme provides code snippets and explanations for using functions in TypeScript. Functions are an essential part of any programming language, including TypeScript, and they allow you to encapsulate reusable blocks of code. TypeScript, being a superset of JavaScript, provides additional features to enhance function typing and readability. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction to Functions](#introduction-to-functions) 8 | 2. [Function Declarations](#function-declarations) 9 | 3. [Function Expressions](#function-expressions) 10 | 4. [Arrow Functions](#arrow-functions) 11 | 5. [Optional and Default Parameters](#optional-and-default-parameters) 12 | 6. [Rest Parameters](#rest-parameters) 13 | 7. [Function Overloading](#function-overloading) 14 | 15 | ## Introduction to Functions 16 | 17 | A function in TypeScript is a block of code designed to perform a specific task or calculation. Functions help break down complex tasks into smaller, more manageable pieces, improving code organization and reusability. 18 | 19 | In TypeScript, functions can have explicit type annotations for parameters and return types, allowing for better type safety and IDE support. 20 | 21 | ## Function Declarations 22 | 23 | ```typescript 24 | function greet(name: string): string { 25 | return `Hello, ${name}!`; 26 | } 27 | ``` 28 | 29 | - The `function` keyword is used to declare a function. 30 | - `greet` is the function name. 31 | - `(name: string)` is the parameter list with type annotations. 32 | - `: string` specifies the return type of the function. 33 | 34 | ## Function Expressions 35 | 36 | ```typescript 37 | const multiply = function (a: number, b: number): number { 38 | return a * b; 39 | }; 40 | ``` 41 | 42 | - Function expressions create anonymous functions assigned to variables. 43 | - `multiply` is a variable that holds the function. 44 | - `(a: number, b: number)` defines the function's parameters with type annotations. 45 | - `: number` specifies the return type of the function. 46 | 47 | ## Arrow Functions 48 | 49 | ```typescript 50 | const divide = (a: number, b: number): number => a / b; 51 | ``` 52 | 53 | - Arrow functions provide a concise syntax for writing functions. 54 | - `divide` is a variable holding the arrow function. 55 | - `(a: number, b: number)` specifies the parameters with type annotations. 56 | - `: number` indicates the return type of the function. 57 | - `=>` is the arrow notation for defining functions. 58 | 59 | ## Optional and Default Parameters 60 | 61 | ```typescript 62 | function greetPerson(name: string, age?: number): string { 63 | if (age) { 64 | return `Hello, ${name}! You are ${age} years old.`; 65 | } else { 66 | return `Hello, ${name}!`; 67 | } 68 | } 69 | 70 | function getDiscount(price: number, percentage: number = 10): number { 71 | return price * (percentage / 100); 72 | } 73 | ``` 74 | 75 | - The `age?` parameter is optional, denoted by the `?` symbol. 76 | - Optional parameters allow calling the function with or without providing that parameter. 77 | - `percentage: number = 10` assigns a default value of 10 to the `percentage` parameter if it is not provided. 78 | 79 | ## Rest Parameters 80 | 81 | ```typescript 82 | function sumNumbers(...numbers: number[]): number { 83 | return numbers.reduce((sum, num) => sum + num, 0); 84 | } 85 | ``` 86 | 87 | - Rest parameters denoted by `...` allow the function to accept an arbitrary number of arguments as an array. 88 | - The `numbers: number[]` syntax indicates that `numbers` is an array of numbers. 89 | 90 | ## Function Overloading 91 | 92 | ```typescript 93 | function getFullName(firstName: string, lastName: string): string; 94 | function getFullName( 95 | firstName: string, 96 | middleName: string, 97 | lastName: string 98 | ): string; 99 | function getFullName(...args: string[]): string { 100 | if (args.length === 2) { 101 | return `${args[0]} ${args[1]}`; 102 | } else if (args.length === 3) { 103 | return `${args[0]} ${args[1]} ${args[2]}`; 104 | } 105 | throw new Error("Invalid number of arguments."); 106 | } 107 | ``` 108 | 109 | - Function overloading allows defining multiple function signatures for the same function name. 110 | - The actual implementation is provided in the last function with the rest parameter `...args: string[]`. 111 | 112 | These code snippets and explanations cover the essential aspects of using functions in TypeScript. Functions play a crucial role in structuring and organizing code, enabling code reusability and enhancing readability. TypeScript's strong typing system empowers developers to write more reliable and maintainable functions, leading to better software development practices. 113 | 114 | For more advanced TypeScript concepts and features, please refer to the [official TypeScript documentation ](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) 115 | -------------------------------------------------------------------------------- /03 objects/01-object.ts: -------------------------------------------------------------------------------- 1 | //function getUserData({ userName: string, password: string }) {} 2 | 3 | function getUserData({ 4 | userName, 5 | password, 6 | }: { 7 | userName: string; 8 | password: string; 9 | }) {} 10 | 11 | getUserData({ userName: "arvindpandit", password: "arvindPassword12345" }); 12 | -------------------------------------------------------------------------------- /03 objects/02-object.ts: -------------------------------------------------------------------------------- 1 | function getOTP(access: boolean): { otp: number } { 2 | return { 3 | otp: Math.random(), 4 | }; 5 | } 6 | 7 | getOTP(true); 8 | -------------------------------------------------------------------------------- /03 objects/03-object.ts: -------------------------------------------------------------------------------- 1 | type userInformation = { 2 | readonly id: number; //cannot change 3 | name: string; 4 | password: string; 5 | username: string; 6 | credcardDetails?: number; //optional 7 | }; 8 | 9 | let userFirst: userInformation = { 10 | id: 1, 11 | name: "arvind", 12 | password: "arvindpandit123", 13 | username: "arvindpndit", 14 | }; 15 | 16 | function userInfo(userInfo: userInformation) { 17 | console.log(userInfo.id + userInfo.name); 18 | } 19 | 20 | userInfo(userFirst); 21 | -------------------------------------------------------------------------------- /03 objects/objects.md: -------------------------------------------------------------------------------- 1 | # Objects in TypeScript 2 | 3 | This readme provides code snippets and explanations for working with objects in TypeScript. Objects are a fundamental data structure that allows you to store and organize related data as key-value pairs. TypeScript adds static typing to objects, making it more predictable and providing better tooling support. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction to Objects](#introduction-to-objects) 8 | 2. [Object Literal](#object-literal) 9 | 3. [Type Annotations for Objects](#type-annotations-for-objects) 10 | 4. [Interface for Objects](#interface-for-objects) 11 | 5. [Optional Properties](#optional-properties) 12 | 6. [Readonly Properties](#readonly-properties) 13 | 7. [Nesting Objects](#nesting-objects) 14 | 15 | ## Introduction to Objects 16 | 17 | An object in TypeScript is a collection of key-value pairs, where each key is a unique identifier (string or symbol) and each value can be of any data type, including other objects. 18 | 19 | ## Object Literal 20 | 21 | ```typescript 22 | const person = { 23 | name: "Arvind Pandit", 24 | age: 30, 25 | isStudent: true, 26 | }; 27 | ``` 28 | 29 | - The object `person` is created using an object literal syntax. 30 | - The keys are `name`, `age`, and `isStudent`, and the corresponding values are `"Arvind Pandit"`, `30`, and `true`. 31 | 32 | ## Type Annotations for Objects 33 | 34 | ```typescript 35 | type Person = { 36 | name: string; 37 | age: number; 38 | isStudent: boolean; 39 | }; 40 | 41 | const person: Person = { 42 | name: "Arvind Pandit", 43 | age: 30, 44 | isStudent: true, 45 | }; 46 | ``` 47 | 48 | - We define a `Person` type with explicit type annotations for each property. 49 | - The `person` variable is declared as type `Person`, ensuring that it conforms to the defined structure. 50 | 51 | ## Interface for Objects 52 | 53 | ```typescript 54 | interface Car { 55 | brand: string; 56 | model: string; 57 | year: number; 58 | } 59 | 60 | const myCar: Car = { 61 | brand: "Toyota", 62 | model: "Camry", 63 | year: 2020, 64 | }; 65 | ``` 66 | 67 | - An interface `Car` defines the structure of the object, similar to a type. 68 | - The `myCar` variable is of type `Car`, adhering to the specified interface. 69 | 70 | ## Optional Properties 71 | 72 | ```typescript 73 | interface Employee { 74 | name: string; 75 | age?: number; 76 | department: string; 77 | } 78 | 79 | const employee1: Employee = { 80 | name: "Alice", 81 | department: "HR", 82 | }; 83 | 84 | const employee2: Employee = { 85 | name: "Bob", 86 | age: 25, 87 | department: "Engineering", 88 | }; 89 | ``` 90 | 91 | - The `age?` property is optional, denoted by the `?` symbol. 92 | - Optional properties can be omitted when creating objects of the interface. 93 | 94 | ## Readonly Properties 95 | 96 | ```typescript 97 | interface Point { 98 | readonly x: number; 99 | readonly y: number; 100 | } 101 | 102 | const point: Point = { 103 | x: 10, 104 | y: 20, 105 | }; 106 | 107 | // Error: Cannot assign to 'x' because it is a read-only property. 108 | point.x = 5; 109 | ``` 110 | 111 | - `readonly` keyword makes the properties of the object read-only. 112 | - Once assigned, the values of read-only properties cannot be changed. 113 | 114 | ## Nesting Objects 115 | 116 | ```typescript 117 | interface Address { 118 | street: string; 119 | city: string; 120 | } 121 | 122 | interface Person { 123 | name: string; 124 | age: number; 125 | address: Address; 126 | } 127 | 128 | const person: Person = { 129 | name: "Arvind Pandit", 130 | age: 28, 131 | address: { 132 | street: "123 Main St", 133 | city: "New York", 134 | }, 135 | }; 136 | ``` 137 | 138 | - Objects can be nested within other objects, creating complex data structures. 139 | - In this example, the `Person` interface contains another object `Address` as one of its properties. 140 | 141 | These code snippets and explanations cover the essential aspects of working with objects in TypeScript. Leveraging TypeScript's static typing and interfaces helps ensure that objects adhere to specific structures, leading to more robust and maintainable code. With TypeScript, you can create predictable and structured data representations, enabling better collaboration and development practices. 142 | 143 | For more advanced TypeScript concepts and features, please refer to the [official TypeScript documentation ](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) 144 | 145 | Happy coding! 146 | -------------------------------------------------------------------------------- /04 arrays/01-array.ts: -------------------------------------------------------------------------------- 1 | const students: string[] = ["arvind", "arvind2", "arvind3"]; 2 | 3 | const marks: number[] = [89, 78, 76, 88, 98]; 4 | 5 | const products: Array = ["maggie", "namkeen", "rice"]; 6 | 7 | products.push("fruits"); 8 | //products.push(6); throws an error 9 | -------------------------------------------------------------------------------- /04 arrays/02-arrray.ts: -------------------------------------------------------------------------------- 1 | const rbgConfig: Array> = [ 2 | [223, 434, 112], 3 | [222, 434, 122], 4 | [223, 453, 152], 5 | ]; 6 | -------------------------------------------------------------------------------- /04 arrays/arrays.md: -------------------------------------------------------------------------------- 1 | # Arrays in TypeScript 2 | 3 | This readme provides code snippets and explanations for working with arrays in TypeScript. Arrays are a fundamental data structure that allows you to store and manipulate multiple values of the same type. TypeScript enhances arrays with type annotations, making it more predictable and enabling better tooling support. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction to Arrays](#introduction-to-arrays) 8 | 2. [Array Type Annotations](#array-type-annotations) 9 | 3. [Array Initialization](#array-initialization) 10 | 4. [Array Methods](#array-methods) 11 | - [Push and Pop](#push-and-pop) 12 | - [Shift and Unshift](#shift-and-unshift) 13 | - [Slice](#slice) 14 | - [Map](#map) 15 | - [Filter](#filter) 16 | - [Reduce](#reduce) 17 | - [forEach](#foreach) 18 | 5. [Multi-dimensional Arrays](#multi-dimensional-arrays) 19 | 20 | ## Introduction to Arrays 21 | 22 | An array in TypeScript is an ordered collection of elements of the same type. Arrays allow you to store and manipulate data in a structured manner, making it easier to work with large sets of data. 23 | 24 | ## Array Type Annotations 25 | 26 | ```typescript 27 | let numbers: number[] = [1, 2, 3, 4, 5]; 28 | let names: string[] = ["Alice", "Bob", "Charlie"]; 29 | ``` 30 | 31 | - Array type annotations specify that the `numbers` array contains numbers, and the `names` array contains strings. 32 | - The `number[]` and `string[]` syntax is used to define arrays of specific types. 33 | 34 | ## Array Initialization 35 | 36 | ```typescript 37 | let fruits: string[] = []; 38 | fruits.push("apple"); 39 | fruits.push("banana"); 40 | fruits.push("orange"); 41 | ``` 42 | 43 | - Arrays can be initialized as empty, and elements can be added using the `push()` method. 44 | 45 | ## Array Methods 46 | 47 | ### Push and Pop 48 | 49 | ```typescript 50 | let stack: number[] = []; 51 | stack.push(1); // stack: [1] 52 | stack.push(2); // stack: [1, 2] 53 | let topElement: number = stack.pop(); // topElement: 2, stack: [1] 54 | ``` 55 | 56 | - The `push()` method adds elements to the end of the array. 57 | - The `pop()` method removes and returns the last element from the array. 58 | 59 | ### Shift and Unshift 60 | 61 | ```typescript 62 | let queue: string[] = []; 63 | queue.unshift("first"); // queue: ["first"] 64 | queue.unshift("second"); // queue: ["second", "first"] 65 | let firstElement: string = queue.shift(); // firstElement: "second", queue: ["first"] 66 | ``` 67 | 68 | - The `unshift()` method adds elements to the beginning of the array. 69 | - The `shift()` method removes and returns the first element from the array. 70 | 71 | ### Slice 72 | 73 | ```typescript 74 | let numbers: number[] = [1, 2, 3, 4, 5]; 75 | let slicedNumbers: number[] = numbers.slice(1, 4); // slicedNumbers: [2, 3, 4] 76 | ``` 77 | 78 | - The `slice()` method returns a new array containing elements from the specified start index (inclusive) to the specified end index (exclusive). 79 | 80 | ### Map 81 | 82 | ```typescript 83 | let numbers: number[] = [1, 2, 3, 4, 5]; 84 | let doubledNumbers: number[] = numbers.map((num) => num * 2); // doubledNumbers: [2, 4, 6, 8, 10] 85 | ``` 86 | 87 | - The `map()` method creates a new array by applying a provided function to each element of the original array. 88 | 89 | ### Filter 90 | 91 | ```typescript 92 | let numbers: number[] = [1, 2, 3, 4, 5]; 93 | let evenNumbers: number[] = numbers.filter((num) => num % 2 === 0); // evenNumbers: [2, 4] 94 | ``` 95 | 96 | - The `filter()` method creates a new array with all elements that pass the test implemented by the provided function. 97 | 98 | ### Reduce 99 | 100 | ```typescript 101 | let numbers: number[] = [1, 2, 3, 4, 5]; 102 | let sum: number = numbers.reduce((acc, num) => acc + num, 0); // sum: 15 103 | ``` 104 | 105 | - The `reduce()` method applies a function to each element of the array, reducing it to a single value. 106 | 107 | ### forEach 108 | 109 | ```typescript 110 | let numbers: number[] = [1, 2, 3, 4, 5]; 111 | numbers.forEach((num) => console.log(num)); 112 | ``` 113 | 114 | - The `forEach()` method executes a provided function once for each array element. 115 | 116 | ## Multi-dimensional Arrays 117 | 118 | ```typescript 119 | let matrix: number[][] = [ 120 | [1, 2, 3], 121 | [4, 5, 6], 122 | [7, 8, 9], 123 | ]; 124 | ``` 125 | 126 | - Multi-dimensional arrays are arrays of arrays, forming a matrix or grid-like structure. 127 | 128 | These code snippets and explanations cover the essential aspects of working with arrays in TypeScript. Arrays are powerful data structures that allow you to perform various operations efficiently. With TypeScript's type annotations and enhanced tooling support, you can write more reliable and maintainable code when dealing with arrays in your projects. 129 | 130 | For more advanced TypeScript concepts and features, please refer to the [official TypeScript documentation ](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) 131 | 132 | Happy coding! 133 | -------------------------------------------------------------------------------- /05 tuple/01-tuple.ts: -------------------------------------------------------------------------------- 1 | const randomArray: (number | string)[] = [1, "2", "3", 4, 5]; 2 | 3 | let randomArray2: [number, string, string]; 4 | randomArray2 = [2, "arvind", "ts"]; 5 | 6 | let rgb: [number, number, number] = [255, 123, 112]; 7 | -------------------------------------------------------------------------------- /05 tuple/02-tuple.ts: -------------------------------------------------------------------------------- 1 | type User = [number, string]; 2 | 3 | const newUser: User = [1, "arvind"]; 4 | 5 | newUser[1] = "arvind pandit"; 6 | 7 | newUser.push("will this be the 2nd element"); //how and why 8 | -------------------------------------------------------------------------------- /05 tuple/tuple.md: -------------------------------------------------------------------------------- 1 | # Tuples in TypeScript 2 | 3 | This readme provides code snippets and explanations for using tuples in TypeScript. Tuples are a specialized data structure that allows you to store a fixed number of elements of different types. TypeScript adds static typing to tuples, making them more predictable and enabling better tooling support. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction to Tuples](#introduction-to-tuples) 8 | 2. [Tuple Type Annotations](#tuple-type-annotations) 9 | 3. [Tuple Initialization](#tuple-initialization) 10 | 4. [Accessing Tuple Elements](#accessing-tuple-elements) 11 | 5. [Modifying Tuple Elements](#modifying-tuple-elements) 12 | 6. [Destructuring Tuples](#destructuring-tuples) 13 | 7. [Using Tuples in Functions](#using-tuples-in-functions) 14 | 15 | ## Introduction to Tuples 16 | 17 | A tuple in TypeScript is an ordered collection of elements of different types. Unlike arrays, where all elements have the same type, tuples allow you to combine elements with distinct types in a specific order. 18 | 19 | ## Tuple Type Annotations 20 | 21 | ```typescript 22 | let person: [string, number, boolean]; 23 | ``` 24 | 25 | - The tuple type annotation `: [string, number, boolean]` specifies that the `person` variable is a tuple with three elements of types `string`, `number`, and `boolean`, in that order. 26 | 27 | ## Tuple Initialization 28 | 29 | ```typescript 30 | let person: [string, number, boolean] = ["John Doe", 30, true]; 31 | ``` 32 | 33 | - The `person` tuple is initialized with three elements: `"John Doe"` of type `string`, `30` of type `number`, and `true` of type `boolean`. 34 | 35 | ## Accessing Tuple Elements 36 | 37 | ```typescript 38 | let person: [string, number, boolean] = ["John Doe", 30, true]; 39 | 40 | let name: string = person[0]; // name: "John Doe" 41 | let age: number = person[1]; // age: 30 42 | let isStudent: boolean = person[2]; // isStudent: true 43 | ``` 44 | 45 | - Tuple elements can be accessed using index positions, just like arrays. 46 | 47 | ## Modifying Tuple Elements 48 | 49 | ```typescript 50 | let person: [string, number, boolean] = ["John Doe", 30, true]; 51 | 52 | person[1] = 31; 53 | person[2] = false; 54 | ``` 55 | 56 | - Tuple elements can be modified directly by assigning new values to them. 57 | 58 | ## Destructuring Tuples 59 | 60 | ```typescript 61 | let person: [string, number, boolean] = ["John Doe", 30, true]; 62 | 63 | let [name, age, isStudent] = person; 64 | 65 | console.log(name); // "John Doe" 66 | console.log(age); // 30 67 | console.log(isStudent); // true 68 | ``` 69 | 70 | - Destructuring allows you to unpack tuple elements into individual variables for easier access and readability. 71 | 72 | ## Using Tuples in Functions 73 | 74 | ```typescript 75 | function getCoordinates(): [number, number] { 76 | return [10, 20]; 77 | } 78 | 79 | let [x, y] = getCoordinates(); 80 | 81 | console.log(x); // 10 82 | console.log(y); // 20 83 | ``` 84 | 85 | - Functions can return tuples, allowing you to return multiple values from a function. 86 | 87 | ## Limitations of Tuples 88 | 89 | Tuples have fixed-length and fixed-type elements, which means that once defined, you cannot add or remove elements, and the types of elements are strictly enforced. While tuples are useful for specific use cases, be cautious when using them extensively, as they can reduce code readability and maintainability. 90 | 91 | These code snippets and explanations cover the essential aspects of using tuples in TypeScript. Tuples provide a concise way to represent fixed-size data structures with elements of different types. With TypeScript's type annotations and static typing, you can ensure that tuples adhere to the specified structure, leading to more reliable and maintainable code. 92 | 93 | For more advanced TypeScript concepts and features, please refer to the [official TypeScript documentation ](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) 94 | 95 | Happy coding! 96 | -------------------------------------------------------------------------------- /06 enums/01-enum.ts: -------------------------------------------------------------------------------- 1 | enum Result { 2 | PASS, 3 | FAIL, 4 | ABSENT, 5 | COMPARTMENT, 6 | } 7 | 8 | const arvind = Result.PASS; 9 | const javascript = Result.ABSENT; 10 | -------------------------------------------------------------------------------- /06 enums/enum.md: -------------------------------------------------------------------------------- 1 | # Enums in TypeScript 2 | 3 | This readme provides code snippets and explanations for using enums in TypeScript. Enums are a powerful feature that allows you to define a set of named constants, providing more readable and self-documenting code. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction to Enums](#introduction-to-enums) 8 | 2. [Enum Declaration](#enum-declaration) 9 | 3. [Enum Values](#enum-values) 10 | 4. [Numeric Enums](#numeric-enums) 11 | 5. [String Enums](#string-enums) 12 | 6. [Heterogeneous Enums](#heterogeneous-enums) 13 | 7. [Enum with Custom Values](#enum-with-custom-values) 14 | 8. [Using Enums in Code](#using-enums-in-code) 15 | 16 | ## Introduction to Enums 17 | 18 | Enums in TypeScript are a way to define a set of named constants, where each constant represents a unique value. Enums make the code more expressive and easier to understand, especially when dealing with fixed sets of related values. 19 | 20 | ## Enum Declaration 21 | 22 | ```typescript 23 | enum Direction { 24 | North, 25 | East, 26 | South, 27 | West, 28 | } 29 | ``` 30 | 31 | - The `enum` keyword is used to declare an enum. 32 | - `Direction` is the name of the enum. 33 | - The constants `North`, `East`, `South`, and `West` represent the possible values of the enum. 34 | 35 | ## Enum Values 36 | 37 | ```typescript 38 | enum Color { 39 | Red, 40 | Green, 41 | Blue, 42 | } 43 | ``` 44 | 45 | By default, enums start with a value of 0 and increment by 1 for each subsequent constant. In this example: 46 | 47 | - `Color.Red` has a value of `0`. 48 | - `Color.Green` has a value of `1`. 49 | - `Color.Blue` has a value of `2`. 50 | 51 | ## Numeric Enums 52 | 53 | ```typescript 54 | enum Day { 55 | Sunday = 1, 56 | Monday, 57 | Tuesday, 58 | Wednesday, 59 | Thursday, 60 | Friday, 61 | Saturday, 62 | } 63 | ``` 64 | 65 | You can explicitly set numeric values for enum constants. If the value is not explicitly set, TypeScript will assign incremental numeric values starting from 0. 66 | 67 | In this example: 68 | 69 | - `Day.Sunday` has a value of `1`. 70 | - `Day.Monday` has a value of `2`. 71 | - And so on, until `Day.Saturday` with a value of `7`. 72 | 73 | ## String Enums 74 | 75 | ```typescript 76 | enum Direction { 77 | North = "NORTH", 78 | East = "EAST", 79 | South = "SOUTH", 80 | West = "WEST", 81 | } 82 | ``` 83 | 84 | Enums can also use string values as constants. Each constant must have a unique string value. 85 | 86 | ## Heterogeneous Enums 87 | 88 | ```typescript 89 | enum MixedEnum { 90 | Zero, 91 | One = "ONE", 92 | Two = 2, 93 | } 94 | ``` 95 | 96 | Enums can have a mix of numeric and string constants. 97 | 98 | ## Enum with Custom Values 99 | 100 | ```typescript 101 | enum ErrorCode { 102 | NotFound = 404, 103 | Unauthorized = 401, 104 | InternalServerError = 500, 105 | } 106 | ``` 107 | 108 | Enums are often used to represent error codes or status codes in APIs. 109 | 110 | ## Using Enums in Code 111 | 112 | ```typescript 113 | enum Color { 114 | Red, 115 | Green, 116 | Blue, 117 | } 118 | 119 | function getColorName(color: Color): string { 120 | switch (color) { 121 | case Color.Red: 122 | return "Red"; 123 | case Color.Green: 124 | return "Green"; 125 | case Color.Blue: 126 | return "Blue"; 127 | default: 128 | return "Unknown"; 129 | } 130 | } 131 | 132 | const selectedColor: Color = Color.Green; 133 | const colorName: string = getColorName(selectedColor); 134 | console.log(colorName); // "Green" 135 | ``` 136 | 137 | Enums are especially useful in switch statements or when you want to map constant values to more descriptive names. 138 | 139 | These code snippets and explanations cover the essential aspects of using enums in TypeScript. Enums provide a way to represent a set of named constants, making the code more expressive and readable. By using enums, you can improve code maintainability and avoid the use of "magic numbers" or arbitrary strings, leading to more reliable and self-documenting code. 140 | 141 | For more advanced TypeScript concepts and features, please refer to the [official TypeScript documentation ](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) 142 | 143 | Happy coding! 144 | -------------------------------------------------------------------------------- /07 union/01-union.ts: -------------------------------------------------------------------------------- 1 | let id: string | number; 2 | 3 | id = 5; 4 | id = "kdfj234"; 5 | 6 | let randomArr: (string | number)[] = ["1", 2, 3, "4"]; 7 | 8 | type User = { 9 | name: string; 10 | id: number; 11 | }; 12 | 13 | type Admin = { 14 | username: string; 15 | id: number; 16 | }; 17 | 18 | let arvind: User | Admin = { name: "arvind", id: 334 }; 19 | 20 | arvind = { username: "arvindpndit", id: 334 }; 21 | -------------------------------------------------------------------------------- /07 union/union.md: -------------------------------------------------------------------------------- 1 | # Union Types in TypeScript 2 | 3 | This readme provides code snippets and explanations for using union types in TypeScript. Union types allow you to express that a value can be of multiple types, offering increased flexibility in type annotations. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction to Union Types](#introduction-to-union-types) 8 | 2. [Union Type Declaration](#union-type-declaration) 9 | 3. [Using Union Types](#using-union-types) 10 | - [Function Parameters](#function-parameters) 11 | - [Return Types](#return-types) 12 | - [Variable Declaration](#variable-declaration) 13 | 4. [Type Guards](#type-guards) 14 | 5. [Using `typeof` with Union Types](#using-typeof-with-union-types) 15 | 16 | ## Introduction to Union Types 17 | 18 | In TypeScript, a union type allows you to specify that a value can be of more than one type. This provides greater flexibility and helps handle scenarios where a function or variable can accept or hold different types of data. 19 | 20 | ## Union Type Declaration 21 | 22 | ```typescript 23 | let variable: string | number; 24 | ``` 25 | 26 | - The `string | number` notation indicates that the `variable` can hold values of type `string` or `number`. 27 | 28 | ## Using Union Types 29 | 30 | ### Function Parameters 31 | 32 | ```typescript 33 | function printId(id: string | number) { 34 | console.log(`ID: ${id}`); 35 | } 36 | 37 | printId("abc"); // Output: ID: abc 38 | printId(123); // Output: ID: 123 39 | ``` 40 | 41 | - The `printId` function takes a parameter of type `string | number`, allowing it to accept both strings and numbers. 42 | 43 | ### Return Types 44 | 45 | ```typescript 46 | function combine(a: string, b: string): string; 47 | function combine(a: number, b: number): number; 48 | function combine(a: string | number, b: string | number): string | number { 49 | return a + b; 50 | } 51 | 52 | let result1: string = combine("Hello, ", "world!"); // result1: "Hello, world!" 53 | let result2: number = combine(5, 10); // result2: 15 54 | ``` 55 | 56 | - The `combine` function is overloaded with two signatures, one for string inputs and another for number inputs. 57 | - The implementation accepts `string | number` parameters and returns `string | number`, combining the inputs. 58 | 59 | ### Variable Declaration 60 | 61 | ```typescript 62 | let value: string | number; 63 | value = "abc"; 64 | console.log(value); // Output: "abc" 65 | 66 | value = 123; 67 | console.log(value); // Output: 123 68 | ``` 69 | 70 | - The `value` variable is declared with a union type `string | number`, allowing it to hold both string and number values. 71 | 72 | ## Type Guards 73 | 74 | ```typescript 75 | function printLength(value: string | number) { 76 | if (typeof value === "string") { 77 | console.log(`Length of the string: ${value.length}`); 78 | } else { 79 | console.log(`The value is a number.`); 80 | } 81 | } 82 | 83 | printLength("hello"); // Output: Length of the string: 5 84 | printLength(42); // Output: The value is a number. 85 | ``` 86 | 87 | - The `typeof` type guard is used to determine the actual type of the value within the conditional block. 88 | 89 | ## Using `typeof` with Union Types 90 | 91 | ```typescript 92 | let result: string | number = "hello"; 93 | 94 | if (typeof result === "string") { 95 | console.log(`The result is a string: ${result.toUpperCase()}`); 96 | } else { 97 | console.log(`The result is a number: ${result.toFixed(2)}`); 98 | } 99 | ``` 100 | 101 | - The `typeof` type guard helps narrow down the type within the `if` block, allowing access to the specific properties and methods of each type. 102 | 103 | These code snippets and explanations cover the essential aspects of using union types in TypeScript. Union types provide increased flexibility in type annotations, allowing functions and variables to accept or hold multiple types of data. Type guards and the use of `typeof` further enhance the capabilities of union types, helping developers write more robust and type-safe code. 104 | 105 | For more advanced TypeScript concepts and features, please refer to the [official TypeScript documentation ](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) 106 | 107 | Happy coding! 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TypeScript from Scratch to Advanced 🚀 2 | 3 | Welcome to the exciting journey of learning TypeScript from the basics to advanced topics! 📚 This repository contains my personal notes and code snippets to help you gain a deeper understanding of TypeScript concepts. 4 | 5 | ## Prerequisites 6 | 7 | Before diving into this learning adventure, make sure you have a basic idea about JavaScript. 💡 8 | 9 | ## Contents 10 | 11 | The repository is divided into several thrilling parts, each delving into a different aspect of TypeScript. Here's a sneak peek at what each part entails: 12 | 13 | ### Part 1: 🎬 The Start (Welcome) 14 | 15 | 1. [What the Heck is TypeScript](https://github.com/arvindpndit/TypeScript/blob/master/01%20hello%20typescript/intro.md) ❓ 16 | 2. [Let's Make Some Variables](https://github.com/arvindpndit/TypeScript/blob/master/01%20hello%20typescript/variable.md) 📦 17 | 18 | ### Part 2: 🎢 The Story (Enjoy) 19 | 20 | 1. [Playing with Functions](https://github.com/arvindpndit/TypeScript/blob/master/02%20functions/functions.md) 🎮 21 | 2. [Take This Object](https://github.com/arvindpndit/TypeScript/blob/master/03%20objects/objects.md) 🧩 22 | 3. [Array is Fun](https://github.com/arvindpndit/TypeScript/blob/master/04%20arrays/arrays.md) 🎉 23 | 4. [Make Tuple but Be Cautious](https://github.com/arvindpndit/TypeScript/blob/master/05%20tuple/tuple.md) 🎭 24 | 5. [Enum Enum Enum](https://github.com/arvindpndit/TypeScript/blob/master/06%20enums/enum.md) 🌌 25 | 6. [That's My Union](https://github.com/arvindpndit/TypeScript/blob/master/07%20union/union.md) 🔗 26 | 27 | ### Part 3: 🏆 The End (Not Really) 28 | 29 | ... Content Loading ⌛ 30 | 31 | ## Contributing 32 | 33 | If you stumble upon any errors or have mind-blowing ideas to enhance this repository, don't hesitate to open an issue or submit a pull request. Your contributions are highly valued and appreciated! ❤️ 34 | 35 | ## Contact 36 | 37 | If you have any questions about this repository or simply want to connect with me, you can find me on LinkedIn at [Arvind Pandit](https://www.linkedin.com/in/arvindpndit/). Let's level up our TypeScript skills together! :rocket: 38 | --------------------------------------------------------------------------------