├── .gitignore ├── README.md ├── package.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | 3 | .DS_Store 4 | 5 | npm-debug.log* 6 | yarn-debug.log* 7 | yarn-error.log* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TypeScript Cheatsheet 2 | 3 | Cheatsheet for TypeScript. Please make an issue if you encounter a problem and PR always welcome. 4 | 5 | ### Table of Contents 6 | 7 |
8 | 9 | Expand Table of Contents 10 | 11 | - [Section 1: Setup](#section-1-setup) 12 | - [Section 2: Data Types](#section-2-data-types) 13 | - [String, Number, Array, Boolean](#string-number-array-boolean) 14 | - [Tuples](#tuples) 15 | - [Enum](#enum) 16 | - [Union](#union) 17 | - [Any](#any) 18 | - [Unknown](#unknown) 19 | - [Void](#void) 20 | - [Never](#never) 21 | - [Partial](#partial) 22 | - [Readonly](#readonly) 23 | - [Pick](#pick) 24 | - [Section 3: Interface](#section-3-interface) 25 | - [Section 4: Type Alias](#section-4-type-alias) 26 | - [Section 5: Class](#section-5-class) 27 | - [Section 6: Generics](#section-6-generics) 28 | - [Section 7: Symbol](#section-7-symbol) 29 | - [Section 8: Keyof & Indexed Access Types](#section-8-keyof-and-indexed-access-types) 30 | - [Section 9: Mapped Types](#section-9-mapped-types) 31 | - [Section 10: Type Guards](#section-10-type-guards) 32 | - [Section 11: Namespaces](#section-11-namespaces) 33 | 34 |
35 | 36 | # Section 1: Setup 37 | 38 | 1. Go to [TypeScript](https://www.typescriptlang.org) download from there or just type `npm install -g typescript`. 39 | 2. Check the installed version `tsc -v`. 40 | 41 | # Section 2: Data Types 42 | 43 | ## String, Number, Array, Boolean 44 | 45 | There are some basic types available for TypeScript. Such as `string`, `number`, `Array`, `string[]`, boolean etc. We can do Type Declaration by them. 46 | 47 | ```ts 48 | let x: number = 5; 49 | let name: string = "John Doe"; 50 | let showErrorMsg: boolean = true; 51 | let numbers: number[] = [1, 2, 3]; 52 | let numbers: Array = [1, 2, 3]; 53 | let students: Array = ["John Doe", "Michael"]; 54 | 55 | function showDetail(name: string, age: number): void { 56 | console.log(name); 57 | } 58 | ``` 59 | 60 | ## Tuples 61 | 62 | This is something new in TypeScript 3. A Tuple is an array but the number of elements are fixed. 63 | 64 | ```ts 65 | let product: [string, number]; 66 | product = ["John", 10]; 67 | 68 | let val: [string, ...number[]]; 69 | val = ["John", 5, 7, 9]; 70 | ``` 71 | 72 | ## Enum 73 | 74 | Enum allows us to declare a set of collection in which we can assign them a perticular value such number, string by default TS compiler will assign them in number. 75 | 76 | ```ts 77 | enum ProgrammingLanguage { 78 | javascript, 79 | python, 80 | php, 81 | } 82 | 83 | // This will be changed as 84 | 85 | enum ProgrammingLanguage { 86 | javascript = 0, 87 | python = 1, 88 | php = 2, 89 | } 90 | ``` 91 | 92 | ## Union 93 | 94 | TypeScript allows us to assign more than one data type for a variable or for a function. 95 | 96 | ```ts 97 | let address: string | number; 98 | address = "New York"; 99 | // or 100 | address = 3100; 101 | 102 | function getValue(): string | number { 103 | return "John Doe"; 104 | // or 105 | return 123; 106 | } 107 | ``` 108 | 109 | ## Any 110 | 111 | If you don't know the actual data type or you don't want to assign a data type you can use `any`. 112 | 113 | ```ts 114 | let detail: any; 115 | detail = "Developer"; 116 | 117 | function getValue(): any { 118 | return "Developer"; 119 | } 120 | ``` 121 | 122 | ## Unknown 123 | 124 | `unknown` is the type-safe counterpart of `any`. Anything is assignable to `unknown`, but `unknown` isn’t assignable to anything but itself. 125 | 126 | ```ts 127 | let value: unknown; 128 | 129 | value.trim(); // Error 130 | value(); // Error 131 | new value(); // Error 132 | ``` 133 | 134 | ## Void 135 | 136 | This is useful when you are not returning anything from the function(this is not mandatory to include). 137 | 138 | ```ts 139 | function getError(): void { 140 | console.log("TypeScript is a SuperSet of JavaScript"); 141 | } 142 | ``` 143 | 144 | ## Never 145 | 146 | Use `never` when a function doesn't return anything. This can be used when a function returns error. 147 | 148 | ```ts 149 | function error(message: string): never { 150 | throw new Error(message); 151 | } 152 | ``` 153 | 154 | ## Partial 155 | 156 | Partial makes all properties of the type optional. 157 | 158 | ```ts 159 | interface User { 160 | id: number; 161 | name: string; 162 | email: string; 163 | } 164 | 165 | let user: Partial = { 166 | id: 1, 167 | }; 168 | ``` 169 | 170 | ## Readonly 171 | 172 | When we use readonly, we can’t assign them with other variables, can’t update or delete. This avoids unexpected mutation. 173 | 174 | ```ts 175 | let students: readonly Array = ["John", "Michael", "Adam"]; 176 | ``` 177 | 178 | ## Pick 179 | 180 | It allows you to create a new type from an existing interface. 181 | 182 | ```ts 183 | interface User { 184 | id: number 185 | name: string 186 | email: string 187 | } 188 | 189 | function foo(args: Pick) { 190 | console.log(args); 191 | } 192 | 193 | foo({ name: "John Doe", email: "doe@gmail.com" }); 194 | ``` 195 | 196 | # Section 3: Interface 197 | 198 | An Interface is a group of properties and methods that describe an object but neither does initialization nor implementation. 199 | 200 | ```ts 201 | interface User { 202 | name: string; 203 | age: number; 204 | getPoints(point: number): number; 205 | } 206 | 207 | let user: User = { 208 | name: "John Doe", 209 | age: 25, 210 | getPoints(point: number): number { 211 | return point * point; 212 | }, 213 | }; 214 | ``` 215 | 216 | We can make properties and parameters optional. 217 | 218 | ```ts 219 | interface User { 220 | name?: string; 221 | age: number; 222 | getPoints(point?: number): number; 223 | } 224 | 225 | let user: User = { 226 | age: 25, 227 | getPoints(): number { 228 | return 5 * 5; 229 | }, 230 | }; 231 | ``` 232 | 233 | # Section 4: Type Alias 234 | 235 | Type Alias creates a new name for a type. 236 | 237 | ```ts 238 | type GetArea = (width: number, height: number) => number; 239 | 240 | interface Rectangle { 241 | getArea: GetArea; 242 | } 243 | 244 | let rectangle: Rectangle = { 245 | getArea(width: number, height: number): number { 246 | return width * height; 247 | }, 248 | }; 249 | ``` 250 | 251 | # Section 5: Class 252 | 253 | Just like the other language TypeScript has a class feature. 254 | 255 | ```ts 256 | class Product { 257 | name: string; 258 | price: number; 259 | 260 | constructor(name: string, price: number) { 261 | this.name = name; 262 | this.price = price; 263 | } 264 | 265 | getTotalPrice(discount: number): number { 266 | return this.price - discount; 267 | } 268 | } 269 | 270 | const product = new Product("Milk", 250); 271 | ``` 272 | 273 | We can add interface for Product class. 274 | 275 | ```ts 276 | interface IProduct { 277 | name: string; 278 | price: number; 279 | getTotalPrice(discount: number): number; 280 | } 281 | 282 | class Product implements IProduct { 283 | name: string; 284 | price: number; 285 | 286 | constructor(name: string, price: number) { 287 | this.name = name; 288 | this.price = price; 289 | } 290 | 291 | getTotalPrice(discount: number): number { 292 | return this.price - discount; 293 | } 294 | } 295 | 296 | const product = new Product("Milk", 250); 297 | ``` 298 | 299 | # Section 6: Generics 300 | 301 | We can specifically pass the type to any function but what if when we don't know the type to pass, Generic can help us. 302 | 303 | ```ts 304 | // Generic Function 305 | function removeItem(arr: Array, item: T): Array { 306 | let index = arr.findIndex((i) => i === item); 307 | arr.splice(index, 1); 308 | return arr; 309 | } 310 | 311 | console.log(removeItem([1, 2, 3], 2)); 312 | console.log(removeItem(["John", "Michael"], "John")); 313 | ``` 314 | 315 | ```ts 316 | // Generic Class 317 | class Country { 318 | protected countryName: string; 319 | 320 | constructor(countryName: string) { 321 | this.countryName = countryName; 322 | } 323 | 324 | getName() { 325 | return this.countryName; 326 | } 327 | } 328 | 329 | class Australia extends Country {} 330 | class England extends Country {} 331 | 332 | let australia = new Australia("Australia"); 333 | let england = new England("England"); 334 | 335 | function getName(country: T): T { 336 | return country; 337 | } 338 | 339 | console.log(getName(australia)); 340 | console.log(getName(england)); 341 | ``` 342 | 343 | # Section 7: Symbol 344 | 345 | Symbol is a primitive data type, which is also immutable and unique. 346 | 347 | ```ts 348 | let sym1 = Symbol("key"); 349 | let sym2 = Symbol("key"); 350 | 351 | sym1 === sym2; // false 352 | ``` 353 | 354 | # Section 8: Keyof & Indexed Access Types 355 | 356 | In TypeScript `keyof` operator extracts the set of keys for a given type. 357 | 358 | ```ts 359 | interface IUser { 360 | name: string; 361 | age: number; 362 | } 363 | 364 | type UserKeys = keyof IUser; // "name" | "age" 365 | ``` 366 | 367 | Using the `keyof` operator we can do Indexed Access Types. The key parameter can get the type of each key of obj. 368 | 369 | ```ts 370 | function getValue(obj: T, key: K): T[K] { 371 | return obj[key]; 372 | } 373 | 374 | const user = { 375 | id: 1, 376 | name: "John Doe", 377 | }; 378 | 379 | console.log(getValue(user, "id")); // 1 380 | ``` 381 | 382 | # Section 9: Mapped Types 383 | 384 | In TypeScript Mapped Types allow us to create new types from existing types. 385 | 386 | ```ts 387 | interface Person { 388 | name: string; 389 | age: number; 390 | } 391 | 392 | type readonlyPerson = { 393 | readonly [P in keyof Person]: Person[p]; 394 | }; 395 | ``` 396 | 397 | # Section 10: Type Guards 398 | 399 | In order to find specific type when we use union types, we can use the Type Guard. `typeof`, `instanceof`, `in` are the examples of Type Guard. 400 | 401 | ```ts 402 | // typeof 403 | function showMessage(message: string | object): void { 404 | if (typeof message === "string") { 405 | console.log("The type is string"); 406 | } else if (typeof message === "object") { 407 | console.log("The type is object"); 408 | } 409 | } 410 | 411 | showMessage({ name: "John Doe" }); 412 | ``` 413 | 414 | ```ts 415 | // instanceof 416 | class User { 417 | id: number; 418 | } 419 | 420 | class Product { 421 | name: string; 422 | } 423 | 424 | function showMessage(message: User | Product): void { 425 | if (message instanceof User) { 426 | console.log("Message is an instance of User"); 427 | } else if (message instanceof Product) { 428 | console.log("Message is an instance of Product"); 429 | } 430 | } 431 | 432 | showMessage(new User()); 433 | ``` 434 | 435 | # Section 11 Namespaces 436 | 437 | You might have come across the term `namespace` while working with TypeScript. And you might wonder what on earth is a namespace? We will be dealing with the basic concepts of namespaces and how we can use them to write efficient codes. 438 | 439 | ```ts 440 | namespace AcmeCorp.Logging { 441 | export class Logger { 442 | static log(msg: string) : void { 443 | console.log(msg); 444 | }; 445 | } 446 | } 447 | 448 | /// 449 | 450 | //Alias 451 | import logger = AcmeCorp.Logging.Logger; 452 | 453 | namespace AcmeCorp.OnlineStore { 454 | class OrderLogic { 455 | calcOrder(): number { 456 | logger.log("calculating order"); 457 | return 0; 458 | } 459 | } 460 | } 461 | ``` 462 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typescript-cheatsheet", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "scripts": { 6 | "format": "prettier --write README.md" 7 | }, 8 | "repository": "https://github.com/lahin31/typescript-cheatsheet.git", 9 | "author": "lahin31 ", 10 | "license": "MIT", 11 | "devDependencies": { 12 | "prettier": "^1.19.1" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | prettier@^1.19.1: 6 | version "1.19.1" 7 | resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb" 8 | integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew== 9 | --------------------------------------------------------------------------------