├── LICENSE ├── README.md └── assets └── star.png /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Pradeep Kumar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Typescript Basics 2 | 3 | > *Click ★ if you like the project. Your contributions are heartily ♡ welcome.* 4 | 5 |
6 | 7 | ## Q. What are the typescript features? 8 | 9 | **TypeScript** is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. 10 | Typescript is an extension of ES6. 11 | 12 | * TypeScript includes **Interfaces**, **Classes**, **Enums**, **Type Inference**, **Generics**, **access modifiers**, **Function** etc. TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. 13 | 14 | * TypeScript supports new ECMAScript standards and compiles them to (older) ECMAScript targets of your choosing. This means that you can use features of ES2015 and beyond, like modules, lambda functions, classes, the spread operator, destructuring etc. 15 | 16 | * With strict null checks enabled (`--strictNullChecks` compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. 17 | 18 | * The TypeScript compiler can inline source map information in the generated `.js` files or create separate `.map` files. This makes it possible to set breakpoints and inspect variables during runtime directly on TypeScript code. 19 | 20 |
21 | ↥ back to top 22 |
23 | 24 | ## Q. How to pass optional parameter in typescript? 25 | 26 | Optional Parameter Syntax 27 | 28 | ```ts 29 | function functionName(par1: number, par2?: number) { 30 | 31 | } 32 | ``` 33 | 34 | **Example:** 35 | 36 | ```ts 37 | function getSchool(name: string, address?: string, pinCode?: string): string { 38 |     //... 39 | } 40 |   41 | let school = getSchool("Elementary"); 42 | let school2 = getSchool("Little Kid", "UK");  43 | let school3 = getSchool("Rose Tree School", "US", "99501") 44 | ``` 45 | 46 |
47 | ↥ back to top 48 |
49 | 50 | ## Q. How to declare variable so that it can hold multiple values? 51 | 52 | **Tuples:** 53 | 54 | It represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions. 55 | 56 | **Syntax:** 57 | 58 | ```ts 59 | let tuple_name = [value1, value2, value3,… value n] 60 | ``` 61 | 62 | **Example:** 63 | 64 | ```ts 65 | let employee: [number, string] = [10, "Pradeep"]; // Create a tuple 66 | console.log(employee[0]); // Output: 10 67 | console.log(employee[1]); // Output: Pradeep 68 | ``` 69 | 70 |
71 | ↥ back to top 72 |
73 | 74 | ## Q. Explain generics in TypeScript? 75 | 76 | Generics offer a way to create reusable components. Generics provide a way to make components work with any data type and not restrict to one data type. 77 | 78 | **Example:** 79 | 80 | ```ts 81 | /** 82 | * Generics 83 | */ 84 | function getArray(items : T[] ) : T[] { 85 | return new Array().concat(items); 86 | } 87 | 88 | let numArr = getArray([10, 20, 30]); 89 | let strArr = getArray(["Hello", "World"]); 90 | 91 | numArr.push(40); // OK 92 | strArr.push("Hello TypeScript"); // OK 93 | 94 | numArr.push("Hi"); // Compiler Error 95 | strArr.push(50); // Compiler Error 96 | ``` 97 | 98 |
99 | ↥ back to top 100 |
101 | 102 | ## Q. How to implement class constants in TypeScript? 103 | 104 | In TypeScript, the **const** keyword cannot be used to declare class properties. Doing so causes the compiler to an error with **A class member cannot have the 'const' keyword.** TypeScript 2.0 has the **readonly** modifier. 105 | 106 | **Example:** 107 | 108 | ```ts 109 | class MyClass { 110 | readonly myReadonlyProperty = 1; 111 | 112 | myMethod() { 113 | console.log(this.myReadonlyProperty); 114 | } 115 | } 116 | 117 | new MyClass().myReadonlyProperty = 5; // error, readonly 118 | ``` 119 | 120 |
121 | ↥ back to top 122 |
123 | 124 | ## Q. What is getters and setters in TypeScript? 125 | 126 | TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. Getters enable us to bind a property to a function that is called when the property is accessed, whereas setters bind a property to a function that is called on attempts to set the property. 127 | 128 | **Example:** 129 | 130 | ```ts 131 | /** 132 | * Getters and Setters 133 | */ 134 | class Employee { 135 | private _name: string; 136 | 137 | get Name() { 138 | return this._name; 139 | } 140 | set Name(val) { 141 | this._name = val; 142 | } 143 | } 144 | 145 | let employee = new Employee(); 146 | employee.Name = "Pradeep"; 147 | 148 | console.log("Name" + employee.Name); // Pradeep 149 | ``` 150 | 151 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/getter-and-setter-peq1nj?file=/src/index.ts)** 152 | 153 |
154 | ↥ back to top 155 |
156 | 157 | ## Q. Is that TypeScript code valid? 158 | 159 | ```ts 160 | class Point { 161 | x: number; 162 | y: number; 163 | } 164 | 165 | interface Point3d extends Point { 166 | z: number; 167 | } 168 | 169 | let point3d: Point3d = {x: 1, y: 2, z: 3}; 170 | ``` 171 | 172 | Yes, the code is valid. A class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, we can use them in the same places we would be able to use interfaces. 173 | 174 |
175 | ↥ back to top 176 |
177 | 178 | ## Q. Explain decorators in TS? 179 | 180 | Decorators can be used to modify the behavior of a class or become even more powerful when integrated into a framework. For instance, if your framework has methods with restricted access requirements (just for admin), it would be easy to write an `@admin` method decorator to deny access to non-administrative users, or an `@owner` decorator to only allow the owner of an object the ability to modify it. 181 | 182 | **Example:** 183 | 184 | ```ts 185 | /** 186 | * Decorators 187 | */ 188 | class Employee { 189 | get() { } 190 | post() { } 191 | 192 | @admin 193 | delete() { } 194 | 195 | @owner 196 | put() { } 197 | } 198 | ``` 199 | 200 |
201 | ↥ back to top 202 |
203 | 204 | ## Q. What is the difference between interface and type statements? 205 | 206 | |Interface |Type | 207 | |----------|-------| 208 | |An interface declaration always introduces a named object type. |A type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.| 209 | |An interface can be named in an extends or implements clause. |Type alias for an object type literal cannot be named in an |extends or implements clause.| 210 | |Interfaces create a new name that is used everywhere. |Type aliases don\'t create a new name.| 211 | |An interface can have multiple merged declarations. |Type alias for an object type literal cannot have multiple merged declarations.| 212 | 213 | **Example:** 214 | 215 | ```ts 216 | /** 217 | * Interface vs Type 218 | */ 219 | interface X { 220 | a: number 221 | b: string 222 | } 223 | 224 | type X = { 225 | a: number 226 | b: string 227 | }; 228 | ``` 229 | 230 |
231 | ↥ back to top 232 |
233 | 234 | ## Q. What is Rest parameters? 235 | 236 | The rest parameter is used to pass zero or more values to a function. It is declared by prefixing the three **dot** characters **('...')** before the parameter. It allows the functions to have a variable number of arguments without using the arguments object. 237 | 238 | **Rules**: 239 | 240 | * Only one rest parameter is allowed in a function. 241 | * It must be an array type. 242 | * It must be a last parameter in the parameter list. 243 | 244 | **Example:** 245 | 246 | ```ts 247 | /** 248 | * Rest parameters 249 | */ 250 | function sum(a: number, ...b: number[]): number { 251 | let result = a; 252 | for (let i = 0; i < b.length; i++) { 253 | result += b[i]; 254 | } 255 | console.log(result); 256 | } 257 | let result1 = sum(3, 5); 258 | let result2 = sum(3, 5, 7, 9); 259 | ``` 260 | 261 |
262 | ↥ back to top 263 |
264 | 265 | ## Q. Explain enum datatype in TypeScript? 266 | 267 | Enums or enumerations are a TypeScipt data type that allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. It is a collection of related values that can be numeric or string values. 268 | 269 | **Example:** 270 | 271 | ```ts 272 | /** 273 | * Enum Datatype 274 | */ 275 | enum Gender { 276 | Male, 277 | Female 278 | Other 279 | } 280 | console.log(Gender.Female); // Output: 1 281 | //We can also access an enum value by it's number value. 282 | console.log(Gender[1]); // Output: Female 283 | ``` 284 | 285 |
286 | ↥ back to top 287 |
288 | 289 | ## Q. First line below gives compile error, second line doesn\'t. Why? 290 | 291 | ```ts 292 | someService.someMethod(x); 293 | someService['someMethod'](x); 294 | ``` 295 | 296 |
297 | ↥ back to top 298 |
299 | 300 | #### Q. Why do you need type definitions? 301 | #### Q. How would you define a custom type? 302 | #### Q. What is the difference between an Interface and a Class? 303 | #### Q. What are Discriminated union types? 304 | #### Q. How do you define Object of Objects type in typescript? 305 | #### Q. How can you capture the 'type' the user provides (e.g. number), so that we can use that information later. 306 | 307 |
308 | ↥ back to top 309 |
310 | -------------------------------------------------------------------------------- /assets/star.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/typescript-basics/0a7b55b2118445ba6be8d061e9df9a043aa0bf2e/assets/star.png --------------------------------------------------------------------------------