{"id":13452508,"url":"https://github.com/labs42io/clean-code-typescript","last_synced_at":"2025-05-14T01:08:14.071Z","repository":{"id":37663141,"uuid":"167032345","full_name":"labs42io/clean-code-typescript","owner":"labs42io","description":"Clean Code concepts adapted for TypeScript","archived":false,"fork":false,"pushed_at":"2023-11-18T14:14:48.000Z","size":144,"stargazers_count":9280,"open_issues_count":3,"forks_count":1135,"subscribers_count":130,"default_branch":"main","last_synced_at":"2024-10-29T15:35:08.048Z","etag":null,"topics":["best-practices","clean-architecture","clean-code","coding-guidelines","principles","solid","typescript"],"latest_commit_sha":null,"homepage":"https://labs42io.github.io/clean-code-typescript","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/labs42io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2019-01-22T16:58:12.000Z","updated_at":"2024-10-29T11:22:20.000Z","dependencies_parsed_at":"2023-11-18T15:27:39.267Z","dependency_job_id":"803d73b0-6b66-420b-b6dc-50e13601f250","html_url":"https://github.com/labs42io/clean-code-typescript","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/labs42io%2Fclean-code-typescript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/labs42io%2Fclean-code-typescript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/labs42io%2Fclean-code-typescript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/labs42io%2Fclean-code-typescript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/labs42io","download_url":"https://codeload.github.com/labs42io/clean-code-typescript/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248197435,"owners_count":21063619,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["best-practices","clean-architecture","clean-code","coding-guidelines","principles","solid","typescript"],"created_at":"2024-07-31T07:01:26.097Z","updated_at":"2025-04-10T09:48:43.520Z","avatar_url":"https://github.com/labs42io.png","language":"TypeScript","readme":"# clean-code-typescript [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Clean%20Code%20Typescript\u0026url=https://github.com/labs42io/clean-code-typescript)\n\nClean Code concepts adapted for TypeScript.  \nInspired from [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript).\n\n## Table of Contents\n\n  1. [Introduction](#introduction)\n  2. [Variables](#variables)\n  3. [Functions](#functions)\n  4. [Objects and Data Structures](#objects-and-data-structures)\n  5. [Classes](#classes)\n  6. [SOLID](#solid)\n  7. [Testing](#testing)\n  8. [Concurrency](#concurrency)\n  9. [Error Handling](#error-handling)\n  10. [Formatting](#formatting)\n  11. [Comments](#comments)\n  12. [Translations](#translations)\n\n## Introduction\n\n![Humorous image of software quality estimation as a count of how many expletives\nyou shout when reading code](https://www.osnews.com/images/comics/wtfm.jpg)\n\nSoftware engineering principles, from Robert C. Martin's book\n[*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882),\nadapted for TypeScript. This is not a style guide. It's a guide to producing\n[readable, reusable, and refactorable](https://github.com/ryanmcdermott/3rs-of-software-architecture) software in TypeScript.\n\nNot every principle herein has to be strictly followed, and even fewer will be\nuniversally agreed upon. These are guidelines and nothing more, but they are\nones codified over many years of collective experience by the authors of\n*Clean Code*.\n\nOur craft of software engineering is just a bit over 50 years old, and we are\nstill learning a lot. When software architecture is as old as architecture\nitself, maybe then we will have harder rules to follow. For now, let these\nguidelines serve as a touchstone by which to assess the quality of the\nTypeScript code that you and your team produce.\n\nOne more thing: knowing these won't immediately make you a better software\ndeveloper, and working with them for many years doesn't mean you won't make\nmistakes. Every piece of code starts as a first draft, like wet clay getting\nshaped into its final form. Finally, we chisel away the imperfections when\nwe review it with our peers. Don't beat yourself up for first drafts that need\nimprovement. Beat up the code instead!\n\n**[⬆ back to top](#table-of-contents)**\n\n## Variables\n\n### Use meaningful variable names\n\nDistinguish names in such a way that the reader knows what the differences offer.\n\n**Bad:**\n\n```ts\nfunction between\u003cT\u003e(a1: T, a2: T, a3: T): boolean {\n  return a2 \u003c= a1 \u0026\u0026 a1 \u003c= a3;\n}\n\n```\n\n**Good:**\n\n```ts\nfunction between\u003cT\u003e(value: T, left: T, right: T): boolean {\n  return left \u003c= value \u0026\u0026 value \u003c= right;\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use pronounceable variable names\n\nIf you can’t pronounce it, you can’t discuss it without sounding like an idiot.\n\n**Bad:**\n\n```ts\ntype DtaRcrd102 = {\n  genymdhms: Date;\n  modymdhms: Date;\n  pszqint: number;\n}\n```\n\n**Good:**\n\n```ts\ntype Customer = {\n  generationTimestamp: Date;\n  modificationTimestamp: Date;\n  recordId: number;\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use the same vocabulary for the same type of variable\n\n**Bad:**\n\n```ts\nfunction getUserInfo(): User;\nfunction getUserDetails(): User;\nfunction getUserData(): User;\n```\n\n**Good:**\n\n```ts\nfunction getUser(): User;\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use searchable names\n\nWe will read more code than we will ever write. It's important that the code we do write must be readable and searchable. By *not* naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable. Tools like [ESLint](https://typescript-eslint.io/) can help identify unnamed constants (also known as magic strings and magic numbers).\n\n**Bad:**\n\n```ts\n// What the heck is 86400000 for?\nsetTimeout(restart, 86400000);\n```\n\n**Good:**\n\n```ts\n// Declare them as capitalized named constants.\nconst MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; // 86400000\n\nsetTimeout(restart, MILLISECONDS_PER_DAY);\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use explanatory variables\n\n**Bad:**\n\n```ts\ndeclare const users: Map\u003cstring, User\u003e;\n\nfor (const keyValue of users) {\n  // iterate through users map\n}\n```\n\n**Good:**\n\n```ts\ndeclare const users: Map\u003cstring, User\u003e;\n\nfor (const [id, user] of users) {\n  // iterate through users map\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid Mental Mapping\n\nExplicit is better than implicit.  \n*Clarity is king.*\n\n**Bad:**\n\n```ts\nconst u = getUser();\nconst s = getSubscription();\nconst t = charge(u, s);\n```\n\n**Good:**\n\n```ts\nconst user = getUser();\nconst subscription = getSubscription();\nconst transaction = charge(user, subscription);\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't add unneeded context\n\nIf your class/type/object name tells you something, don't repeat that in your variable name.\n\n**Bad:**\n\n```ts\ntype Car = {\n  carMake: string;\n  carModel: string;\n  carColor: string;\n}\n\nfunction print(car: Car): void {\n  console.log(`${car.carMake} ${car.carModel} (${car.carColor})`);\n}\n```\n\n**Good:**\n\n```ts\ntype Car = {\n  make: string;\n  model: string;\n  color: string;\n}\n\nfunction print(car: Car): void {\n  console.log(`${car.make} ${car.model} (${car.color})`);\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use default arguments instead of short circuiting or conditionals\n\nDefault arguments are often cleaner than short circuiting.\n\n**Bad:**\n\n```ts\nfunction loadPages(count?: number) {\n  const loadCount = count !== undefined ? count : 10;\n  // ...\n}\n```\n\n**Good:**\n\n```ts\nfunction loadPages(count: number = 10) {\n  // ...\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use enum to document the intent\n\nEnums can help you document the intent of the code. For example when we are concerned about values being\ndifferent rather than the exact value of those.\n\n**Bad:**\n\n```ts\nconst GENRE = {\n  ROMANTIC: 'romantic',\n  DRAMA: 'drama',\n  COMEDY: 'comedy',\n  DOCUMENTARY: 'documentary',\n}\n\nprojector.configureFilm(GENRE.COMEDY);\n\nclass Projector {\n  // declaration of Projector\n  configureFilm(genre) {\n    switch (genre) {\n      case GENRE.ROMANTIC:\n        // some logic to be executed \n    }\n  }\n}\n```\n\n**Good:**\n\n```ts\nenum GENRE {\n  ROMANTIC,\n  DRAMA,\n  COMEDY,\n  DOCUMENTARY,\n}\n\nprojector.configureFilm(GENRE.COMEDY);\n\nclass Projector {\n  // declaration of Projector\n  configureFilm(genre) {\n    switch (genre) {\n      case GENRE.ROMANTIC:\n        // some logic to be executed \n    }\n  }\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Functions\n\n### Function arguments (2 or fewer ideally)\n\nLimiting the number of function parameters is incredibly important because it makes testing your function easier.\nHaving more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.  \n\nOne or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated.\nUsually, if you have more than two arguments then your function is trying to do too much.\nIn cases where it's not, most of the time a higher-level object will suffice as an argument.  \n\nConsider using object literals if you are finding yourself needing a lot of arguments.  \n\nTo make it obvious what properties the function expects, you can use the [destructuring](https://basarat.gitbook.io/typescript/future-javascript/destructuring) syntax.\nThis has a few advantages:\n\n1. When someone looks at the function signature, it's immediately clear what properties are being used.\n\n2. It can be used to simulate named parameters.\n\n3. Destructuring also clones the specified primitive values of the argument object passed into the function. This can help prevent side effects. Note: objects and arrays that are destructured from the argument object are NOT cloned.\n\n4. TypeScript warns you about unused properties, which would be impossible without destructuring.\n\n**Bad:**\n\n```ts\nfunction createMenu(title: string, body: string, buttonText: string, cancellable: boolean) {\n  // ...\n}\n\ncreateMenu('Foo', 'Bar', 'Baz', true);\n```\n\n**Good:**\n\n```ts\nfunction createMenu(options: { title: string, body: string, buttonText: string, cancellable: boolean }) {\n  // ...\n}\n\ncreateMenu({\n  title: 'Foo',\n  body: 'Bar',\n  buttonText: 'Baz',\n  cancellable: true\n});\n```\n\nYou can further improve readability by using [type aliases](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases):\n\n```ts\n\ntype MenuOptions = { title: string, body: string, buttonText: string, cancellable: boolean };\n\nfunction createMenu(options: MenuOptions) {\n  // ...\n}\n\ncreateMenu({\n  title: 'Foo',\n  body: 'Bar',\n  buttonText: 'Baz',\n  cancellable: true\n});\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Functions should do one thing\n\nThis is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers.\n\n**Bad:**\n\n```ts\nfunction emailActiveClients(clients: Client[]) {\n  clients.forEach((client) =\u003e {\n    const clientRecord = database.lookup(client);\n    if (clientRecord.isActive()) {\n      email(client);\n    }\n  });\n}\n```\n\n**Good:**\n\n```ts\nfunction emailActiveClients(clients: Client[]) {\n  clients.filter(isActiveClient).forEach(email);\n}\n\nfunction isActiveClient(client: Client) {\n  const clientRecord = database.lookup(client);\n  return clientRecord.isActive();\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Function names should say what they do\n\n**Bad:**\n\n```ts\nfunction addToDate(date: Date, month: number): Date {\n  // ...\n}\n\nconst date = new Date();\n\n// It's hard to tell from the function name what is added\naddToDate(date, 1);\n```\n\n**Good:**\n\n```ts\nfunction addMonthToDate(date: Date, month: number): Date {\n  // ...\n}\n\nconst date = new Date();\naddMonthToDate(date, 1);\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Functions should only be one level of abstraction\n\nWhen you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.\n\n**Bad:**\n\n```ts\nfunction parseCode(code: string) {\n  const REGEXES = [ /* ... */ ];\n  const statements = code.split(' ');\n  const tokens = [];\n\n  REGEXES.forEach((regex) =\u003e {\n    statements.forEach((statement) =\u003e {\n      // ...\n    });\n  });\n\n  const ast = [];\n  tokens.forEach((token) =\u003e {\n    // lex...\n  });\n\n  ast.forEach((node) =\u003e {\n    // parse...\n  });\n}\n```\n\n**Good:**\n\n```ts\nconst REGEXES = [ /* ... */ ];\n\nfunction parseCode(code: string) {\n  const tokens = tokenize(code);\n  const syntaxTree = parse(tokens);\n\n  syntaxTree.forEach((node) =\u003e {\n    // parse...\n  });\n}\n\nfunction tokenize(code: string): Token[] {\n  const statements = code.split(' ');\n  const tokens: Token[] = [];\n\n  REGEXES.forEach((regex) =\u003e {\n    statements.forEach((statement) =\u003e {\n      tokens.push( /* ... */ );\n    });\n  });\n\n  return tokens;\n}\n\nfunction parse(tokens: Token[]): SyntaxTree {\n  const syntaxTree: SyntaxTree[] = [];\n  tokens.forEach((token) =\u003e {\n    syntaxTree.push( /* ... */ );\n  });\n\n  return syntaxTree;\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Remove duplicate code\n\nDo your absolute best to avoid duplicate code.\nDuplicate code is bad because it means that there's more than one place to alter something if you need to change some logic.  \n\nImagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc.\nIf you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them.\nIf you only have one list, there's only one place to update!  \n\nOftentimes you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you to have two or more separate functions that do much of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class.  \n\nGetting the abstraction right is critical, that's why you should follow the [SOLID](#solid) principles. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise, you'll find yourself updating multiple places anytime you want to change one thing.\n\n**Bad:**\n\n```ts\nfunction showDeveloperList(developers: Developer[]) {\n  developers.forEach((developer) =\u003e {\n    const expectedSalary = developer.calculateExpectedSalary();\n    const experience = developer.getExperience();\n    const githubLink = developer.getGithubLink();\n\n    const data = {\n      expectedSalary,\n      experience,\n      githubLink\n    };\n\n    render(data);\n  });\n}\n\nfunction showManagerList(managers: Manager[]) {\n  managers.forEach((manager) =\u003e {\n    const expectedSalary = manager.calculateExpectedSalary();\n    const experience = manager.getExperience();\n    const portfolio = manager.getMBAProjects();\n\n    const data = {\n      expectedSalary,\n      experience,\n      portfolio\n    };\n\n    render(data);\n  });\n}\n```\n\n**Good:**\n\n```ts\nclass Developer {\n  // ...\n  getExtraDetails() {\n    return {\n      githubLink: this.githubLink,\n    }\n  }\n}\n\nclass Manager {\n  // ...\n  getExtraDetails() {\n    return {\n      portfolio: this.portfolio,\n    }\n  }\n}\n\nfunction showEmployeeList(employee: (Developer | Manager)[]) {\n  employee.forEach((employee) =\u003e {\n    const expectedSalary = employee.calculateExpectedSalary();\n    const experience = employee.getExperience();\n    const extra = employee.getExtraDetails();\n\n    const data = {\n      expectedSalary,\n      experience,\n      extra,\n    };\n\n    render(data);\n  });\n}\n```\n\nYou may also consider adding a union type, or common parent class if it suits your abstraction.\n```ts\nclass Developer {\n  // ...\n}\n\nclass Manager {\n  // ...\n}\n\ntype Employee = Developer | Manager\n\nfunction showEmployeeList(employee: Employee[]) {\n  // ...\n  });\n}\n\n```\n\nYou should be critical about code duplication. Sometimes there is a tradeoff between duplicated code and increased complexity by introducing unnecessary abstraction. When two implementations from two different modules look similar but live in different domains, duplication might be acceptable and preferred over extracting the common code. The extracted common code, in this case, introduces an indirect dependency between the two modules.\n\n**[⬆ back to top](#table-of-contents)**\n\n### Set default objects with Object.assign or destructuring\n\n**Bad:**\n\n```ts\ntype MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean };\n\nfunction createMenu(config: MenuConfig) {\n  config.title = config.title || 'Foo';\n  config.body = config.body || 'Bar';\n  config.buttonText = config.buttonText || 'Baz';\n  config.cancellable = config.cancellable !== undefined ? config.cancellable : true;\n\n  // ...\n}\n\ncreateMenu({ body: 'Bar' });\n```\n\n**Good:**\n\n```ts\ntype MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean };\n\nfunction createMenu(config: MenuConfig) {\n  const menuConfig = Object.assign({\n    title: 'Foo',\n    body: 'Bar',\n    buttonText: 'Baz',\n    cancellable: true\n  }, config);\n\n  // ...\n}\n\ncreateMenu({ body: 'Bar' });\n```\n\nOr, you could use the spread operator:\n\n```ts\nfunction createMenu(config: MenuConfig) {\n  const menuConfig = {\n    title: 'Foo',\n    body: 'Bar',\n    buttonText: 'Baz',\n    cancellable: true,\n    ...config,\n  };\n\n  // ...\n}\n```\nThe spread operator and `Object.assign()` are very similar.\nThe main difference is that spreading defines new properties, while `Object.assign()` sets them. More detailed, the difference is explained in [this](https://stackoverflow.com/questions/32925460/object-spread-vs-object-assign) thread.\n\nAlternatively, you can use destructuring with default values:\n\n```ts\ntype MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean };\n\nfunction createMenu({ title = 'Foo', body = 'Bar', buttonText = 'Baz', cancellable = true }: MenuConfig) {\n  // ...\n}\n\ncreateMenu({ body: 'Bar' });\n```\n\nTo avoid any side effects and unexpected behavior by passing in explicitly the `undefined` or `null` value, you can tell the TypeScript compiler to not allow it.\nSee [`--strictNullChecks`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#--strictnullchecks) option in TypeScript.\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't use flags as function parameters\n\nFlags tell your user that this function does more than one thing.\nFunctions should do one thing. Split out your functions if they are following different code paths based on a boolean.\n\n**Bad:**\n\n```ts\nfunction createFile(name: string, temp: boolean) {\n  if (temp) {\n    fs.create(`./temp/${name}`);\n  } else {\n    fs.create(name);\n  }\n}\n```\n\n**Good:**\n\n```ts\nfunction createTempFile(name: string) {\n  createFile(`./temp/${name}`);\n}\n\nfunction createFile(name: string) {\n  fs.create(name);\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid Side Effects (part 1)\n\nA function produces a side effect if it does anything other than take a value in and return another value or values.\nA side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a stranger.  \n\nNow, you do need to have side effects in a program on occasion. Like the previous example, you might need to write to a file.\nWhat you want to do is to centralize where you are doing this. Don't have several functions and classes that write to a particular file.\nHave one service that does it. One and only one.  \n\nThe main point is to avoid common pitfalls like sharing state between objects without any structure, using mutable data types that can be written to by anything, and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers.\n\n**Bad:**\n\n```ts\n// Global variable referenced by following function.\nlet name = 'Robert C. Martin';\n\nfunction toBase64() {\n  name = btoa(name);\n}\n\ntoBase64();\n// If we had another function that used this name, now it'd be a Base64 value\n\nconsole.log(name); // expected to print 'Robert C. Martin' but instead 'Um9iZXJ0IEMuIE1hcnRpbg=='\n```\n\n**Good:**\n\n```ts\nconst name = 'Robert C. Martin';\n\nfunction toBase64(text: string): string {\n  return btoa(text);\n}\n\nconst encodedName = toBase64(name);\nconsole.log(name);\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid Side Effects (part 2)\n\nBrowsers and Node.js process only JavaScript, therefore any TypeScript code has to be compiled before running or debugging.  In JavaScript, some values are unchangeable (immutable) and some are changeable (mutable). Objects and arrays are two kinds of mutable values so it's important to handle them carefully when they're passed as parameters to a function. A JavaScript function can change an object's properties or alter the contents of an array which could easily cause bugs elsewhere.\n\nSuppose there's a function that accepts an array parameter representing a shopping cart. If the function makes a change in that shopping cart array - by adding an item to purchase, for example - then any other function that uses that same `cart` array will be affected by this addition. That may be great, however it could also be bad. Let's imagine a bad situation:\n\nThe user clicks the \"Purchase\" button which calls a `purchase` function that spawns a network request and sends the `cart` array to the server. Because of a bad network connection, the `purchase` function has to keep retrying the request. Now, what if in the meantime the user accidentally clicks an \"Add to Cart\" button on an item they don't actually want before the network request begins? If that happens and the network request begins, then that purchase function will send the accidentally added item because the `cart` array was modified.\n\nA great solution would be for the `addItemToCart` function to always clone the `cart`, edit it, and return the clone. This would ensure that functions that are still using the old shopping cart wouldn't be affected by the changes.\n\nTwo caveats to mention to this approach:\n\n1. There might be cases where you actually want to modify the input object, but when you adopt this programming practice you will find that those cases are pretty rare. Most things can be refactored to have no side effects! (see [pure function](https://en.wikipedia.org/wiki/Pure_function))\n\n2. Cloning big objects can be very expensive in terms of performance. Luckily, this isn't a big issue in practice because there are [great libraries](https://github.com/immutable-js/immutable-js) that allow this kind of programming approach to be fast and not as memory intensive as it would be for you to manually clone objects and arrays.\n\n**Bad:**\n\n```ts\nfunction addItemToCart(cart: CartItem[], item: Item): void {\n  cart.push({ item, date: Date.now() });\n};\n```\n\n**Good:**\n\n```ts\nfunction addItemToCart(cart: CartItem[], item: Item): CartItem[] {\n  return [...cart, { item, date: Date.now() }];\n};\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't write to global functions\n\nPolluting globals is a bad practice in JavaScript because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to extend JavaScript's native Array method to have a `diff` method that could show the difference between two arrays? You could write your new function to the `Array.prototype`, but it could clash with another library that tried to do the same thing. What if that other library was just using `diff` to find the difference between the first and last elements of an array? This is why it would be much better to just use classes and simply extend the `Array` global.\n\n**Bad:**\n\n```ts\ndeclare global {\n  interface Array\u003cT\u003e {\n    diff(other: T[]): Array\u003cT\u003e;\n  }\n}\n\nif (!Array.prototype.diff) {\n  Array.prototype.diff = function \u003cT\u003e(other: T[]): T[] {\n    const hash = new Set(other);\n    return this.filter(elem =\u003e !hash.has(elem));\n  };\n}\n```\n\n**Good:**\n\n```ts\nclass MyArray\u003cT\u003e extends Array\u003cT\u003e {\n  diff(other: T[]): T[] {\n    const hash = new Set(other);\n    return this.filter(elem =\u003e !hash.has(elem));\n  };\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Favor functional programming over imperative programming\n\nFavor this style of programming when you can.\n\n**Bad:**\n\n```ts\nconst contributions = [\n  {\n    name: 'Uncle Bobby',\n    linesOfCode: 500\n  }, {\n    name: 'Suzie Q',\n    linesOfCode: 1500\n  }, {\n    name: 'Jimmy Gosling',\n    linesOfCode: 150\n  }, {\n    name: 'Gracie Hopper',\n    linesOfCode: 1000\n  }\n];\n\nlet totalOutput = 0;\n\nfor (let i = 0; i \u003c contributions.length; i++) {\n  totalOutput += contributions[i].linesOfCode;\n}\n```\n\n**Good:**\n\n```ts\nconst contributions = [\n  {\n    name: 'Uncle Bobby',\n    linesOfCode: 500\n  }, {\n    name: 'Suzie Q',\n    linesOfCode: 1500\n  }, {\n    name: 'Jimmy Gosling',\n    linesOfCode: 150\n  }, {\n    name: 'Gracie Hopper',\n    linesOfCode: 1000\n  }\n];\n\nconst totalOutput = contributions\n  .reduce((totalLines, output) =\u003e totalLines + output.linesOfCode, 0);\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Encapsulate conditionals\n\n**Bad:**\n\n```ts\nif (subscription.isTrial || account.balance \u003e 0) {\n  // ...\n}\n```\n\n**Good:**\n\n```ts\nfunction canActivateService(subscription: Subscription, account: Account) {\n  return subscription.isTrial || account.balance \u003e 0;\n}\n\nif (canActivateService(subscription, account)) {\n  // ...\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid negative conditionals\n\n**Bad:**\n\n```ts\nfunction isEmailNotUsed(email: string): boolean {\n  // ...\n}\n\nif (isEmailNotUsed(email)) {\n  // ...\n}\n```\n\n**Good:**\n\n```ts\nfunction isEmailUsed(email: string): boolean {\n  // ...\n}\n\nif (!isEmailUsed(email)) {\n  // ...\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid conditionals\n\nThis seems like an impossible task. Upon first hearing this, most people say, \"how am I supposed to do anything without an `if` statement?\" The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, \"well that's great but why would I want to do that?\" The answer is a previous clean code concept we learned: a function should only do one thing. When you have classes and functions that have `if` statements, you are telling your user that your function does more than one thing. Remember, just do one thing.\n\n**Bad:**\n\n```ts\nclass Airplane {\n  private type: string;\n  // ...\n\n  getCruisingAltitude() {\n    switch (this.type) {\n      case '777':\n        return this.getMaxAltitude() - this.getPassengerCount();\n      case 'Air Force One':\n        return this.getMaxAltitude();\n      case 'Cessna':\n        return this.getMaxAltitude() - this.getFuelExpenditure();\n      default:\n        throw new Error('Unknown airplane type.');\n    }\n  }\n\n  private getMaxAltitude(): number {\n    // ...\n  }\n}\n```\n\n**Good:**\n\n```ts\nabstract class Airplane {\n  protected getMaxAltitude(): number {\n    // shared logic with subclasses ...\n  }\n\n  // ...\n}\n\nclass Boeing777 extends Airplane {\n  // ...\n  getCruisingAltitude() {\n    return this.getMaxAltitude() - this.getPassengerCount();\n  }\n}\n\nclass AirForceOne extends Airplane {\n  // ...\n  getCruisingAltitude() {\n    return this.getMaxAltitude();\n  }\n}\n\nclass Cessna extends Airplane {\n  // ...\n  getCruisingAltitude() {\n    return this.getMaxAltitude() - this.getFuelExpenditure();\n  }\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid type checking\n\nTypeScript is a strict syntactical superset of JavaScript and adds optional static type checking to the language.\nAlways prefer to specify types of variables, parameters and return values to leverage the full power of TypeScript features.\nIt makes refactoring more easier.\n\n**Bad:**\n\n```ts\nfunction travelToTexas(vehicle: Bicycle | Car) {\n  if (vehicle instanceof Bicycle) {\n    vehicle.pedal(currentLocation, new Location('texas'));\n  } else if (vehicle instanceof Car) {\n    vehicle.drive(currentLocation, new Location('texas'));\n  }\n}\n```\n\n**Good:**\n\n```ts\ntype Vehicle = Bicycle | Car;\n\nfunction travelToTexas(vehicle: Vehicle) {\n  vehicle.move(currentLocation, new Location('texas'));\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't over-optimize\n\nModern browsers do a lot of optimization under-the-hood at runtime. A lot of times, if you are optimizing then you are just wasting your time. There are good [resources](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers) for seeing where optimization is lacking. Target those in the meantime, until they are fixed if they can be.\n\n**Bad:**\n\n```ts\n// On old browsers, each iteration with uncached `list.length` would be costly\n// because of `list.length` recomputation. In modern browsers, this is optimized.\nfor (let i = 0, len = list.length; i \u003c len; i++) {\n  // ...\n}\n```\n\n**Good:**\n\n```ts\nfor (let i = 0; i \u003c list.length; i++) {\n  // ...\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Remove dead code\n\nDead code is just as bad as duplicate code. There's no reason to keep it in your codebase.\nIf it's not being called, get rid of it! It will still be saved in your version history if you still need it.\n\n**Bad:**\n\n```ts\nfunction oldRequestModule(url: string) {\n  // ...\n}\n\nfunction requestModule(url: string) {\n  // ...\n}\n\nconst req = requestModule;\ninventoryTracker('apples', req, 'www.inventory-awesome.io');\n```\n\n**Good:**\n\n```ts\nfunction requestModule(url: string) {\n  // ...\n}\n\nconst req = requestModule;\ninventoryTracker('apples', req, 'www.inventory-awesome.io');\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use iterators and generators\n\nUse generators and iterables when working with collections of data used like a stream.  \nThere are some good reasons:\n\n- decouples the callee from the generator implementation in a sense that callee decides how many\nitems to access\n- lazy execution, items are streamed on-demand\n- built-in support for iterating items using the `for-of` syntax\n- iterables allow implementing optimized iterator patterns\n\n**Bad:**\n\n```ts\nfunction fibonacci(n: number): number[] {\n  if (n === 1) return [0];\n  if (n === 2) return [0, 1];\n\n  const items: number[] = [0, 1];\n  while (items.length \u003c n) {\n    items.push(items[items.length - 2] + items[items.length - 1]);\n  }\n\n  return items;\n}\n\nfunction print(n: number) {\n  fibonacci(n).forEach(fib =\u003e console.log(fib));\n}\n\n// Print first 10 Fibonacci numbers.\nprint(10);\n```\n\n**Good:**\n\n```ts\n// Generates an infinite stream of Fibonacci numbers.\n// The generator doesn't keep the array of all numbers.\nfunction* fibonacci(): IterableIterator\u003cnumber\u003e {\n  let [a, b] = [0, 1];\n\n  while (true) {\n    yield a;\n    [a, b] = [b, a + b];\n  }\n}\n\nfunction print(n: number) {\n  let i = 0;\n  for (const fib of fibonacci()) {\n    if (i++ === n) break;  \n    console.log(fib);\n  }  \n}\n\n// Print first 10 Fibonacci numbers.\nprint(10);\n```\n\nThere are libraries that allow working with iterables in a similar way as with native arrays, by\nchaining methods like `map`, `slice`, `forEach` etc. See [itiriri](https://www.npmjs.com/package/itiriri) for\nan example of advanced manipulation with iterables (or [itiriri-async](https://www.npmjs.com/package/itiriri-async) for manipulation of async iterables).\n\n```ts\nimport itiriri from 'itiriri';\n\nfunction* fibonacci(): IterableIterator\u003cnumber\u003e {\n  let [a, b] = [0, 1];\n \n  while (true) {\n    yield a;\n    [a, b] = [b, a + b];\n  }\n}\n\nitiriri(fibonacci())\n  .take(10)\n  .forEach(fib =\u003e console.log(fib));\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Objects and Data Structures\n\n### Use getters and setters\n\nTypeScript supports getter/setter syntax.\nUsing getters and setters to access data from objects that encapsulate behavior could be better than simply looking for a property on an object.\n\"Why?\" you might ask. Well, here's a list of reasons:\n\n- When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.\n- Makes adding validation simple when doing a `set`.\n- Encapsulates the internal representation.\n- Easy to add logging and error handling when getting and setting.\n- You can lazy load your object's properties, let's say getting it from a server.\n\n**Bad:**\n\n```ts\ntype BankAccount = {\n  balance: number;\n  // ...\n}\n\nconst value = 100;\nconst account: BankAccount = {\n  balance: 0,\n  // ...\n};\n\nif (value \u003c 0) {\n  throw new Error('Cannot set negative balance.');\n}\n\naccount.balance = value;\n```\n\n**Good:**\n\n```ts\nclass BankAccount {\n  private accountBalance: number = 0;\n\n  get balance(): number {\n    return this.accountBalance;\n  }\n\n  set balance(value: number) {\n    if (value \u003c 0) {\n      throw new Error('Cannot set negative balance.');\n    }\n\n    this.accountBalance = value;\n  }\n\n  // ...\n}\n\n// Now `BankAccount` encapsulates the validation logic.\n// If one day the specifications change, and we need extra validation rule,\n// we would have to alter only the `setter` implementation,\n// leaving all dependent code unchanged.\nconst account = new BankAccount();\naccount.balance = 100;\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Make objects have private/protected members\n\nTypeScript supports `public` *(default)*, `protected` and `private` accessors on class members.  \n\n**Bad:**\n\n```ts\nclass Circle {\n  radius: number;\n  \n  constructor(radius: number) {\n    this.radius = radius;\n  }\n\n  perimeter() {\n    return 2 * Math.PI * this.radius;\n  }\n\n  surface() {\n    return Math.PI * this.radius * this.radius;\n  }\n}\n```\n\n**Good:**\n\n```ts\nclass Circle {\n  constructor(private readonly radius: number) {\n  }\n\n  perimeter() {\n    return 2 * Math.PI * this.radius;\n  }\n\n  surface() {\n    return Math.PI * this.radius * this.radius;\n  }\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Prefer immutability\n\nTypeScript's type system allows you to mark individual properties on an interface/class as *readonly*. This allows you to work in a functional way (an unexpected mutation is bad).  \nFor more advanced scenarios there is a built-in type `Readonly` that takes a type `T` and marks all of its properties as readonly using mapped types (see [mapped types](https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types)).\n\n**Bad:**\n\n```ts\ninterface Config {\n  host: string;\n  port: string;\n  db: string;\n}\n```\n\n**Good:**\n\n```ts\ninterface Config {\n  readonly host: string;\n  readonly port: string;\n  readonly db: string;\n}\n```\n\nFor arrays, you can create a read-only array by using `ReadonlyArray\u003cT\u003e`.\nIt doesn't allow changes such as `push()` and `fill()`, but can use features such as `concat()` and `slice()` that do not change the array's value.\n\n**Bad:**\n\n```ts\nconst array: number[] = [ 1, 3, 5 ];\narray = []; // error\narray.push(100); // array will be updated\n```\n\n**Good:**\n\n```ts\nconst array: ReadonlyArray\u003cnumber\u003e = [ 1, 3, 5 ];\narray = []; // error\narray.push(100); // error\n```\n\nDeclaring read-only arguments in [TypeScript 3.4 is a bit easier](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#improvements-for-readonlyarray-and-readonly-tuples).\n\n```ts\nfunction hoge(args: readonly string[]) {\n  args.push(1); // error\n}\n```\n\nPrefer [const assertions](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#const-assertions) for literal values.\n\n**Bad:**\n\n```ts\nconst config = {\n  hello: 'world'\n};\nconfig.hello = 'world'; // value is changed\n\nconst array  = [ 1, 3, 5 ];\narray[0] = 10; // value is changed\n\n// writable objects is returned\nfunction readonlyData(value: number) {\n  return { value };\n}\n\nconst result = readonlyData(100);\nresult.value = 200; // value is changed\n```\n\n**Good:**\n\n```ts\n// read-only object\nconst config = {\n  hello: 'world'\n} as const;\nconfig.hello = 'world'; // error\n\n// read-only array\nconst array  = [ 1, 3, 5 ] as const;\narray[0] = 10; // error\n\n// You can return read-only objects\nfunction readonlyData(value: number) {\n  return { value } as const;\n}\n\nconst result = readonlyData(100);\nresult.value = 200; // error\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### type vs. interface\n\nUse type when you might need a union or intersection. Use an interface when you want `extends` or `implements`. There is no strict rule, however, use the one that works for you.  \nFor a more detailed explanation refer to this [answer](https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types/54101543#54101543) about the differences between `type` and `interface` in TypeScript.\n\n**Bad:**\n\n```ts\ninterface EmailConfig {\n  // ...\n}\n\ninterface DbConfig {\n  // ...\n}\n\ninterface Config {\n  // ...\n}\n\n//...\n\ntype Shape = {\n  // ...\n}\n```\n\n**Good:**\n\n```ts\n\ntype EmailConfig = {\n  // ...\n}\n\ntype DbConfig = {\n  // ...\n}\n\ntype Config  = EmailConfig | DbConfig;\n\n// ...\n\ninterface Shape {\n  // ...\n}\n\nclass Circle implements Shape {\n  // ...\n}\n\nclass Square implements Shape {\n  // ...\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Classes\n\n### Classes should be small\n\nThe class' size is measured by its responsibility. Following the *Single Responsibility principle* a class should be small.\n\n**Bad:**\n\n```ts\nclass Dashboard {\n  getLanguage(): string { /* ... */ }\n  setLanguage(language: string): void { /* ... */ }\n  showProgress(): void { /* ... */ }\n  hideProgress(): void { /* ... */ }\n  isDirty(): boolean { /* ... */ }\n  disable(): void { /* ... */ }\n  enable(): void { /* ... */ }\n  addSubscription(subscription: Subscription): void { /* ... */ }\n  removeSubscription(subscription: Subscription): void { /* ... */ }\n  addUser(user: User): void { /* ... */ }\n  removeUser(user: User): void { /* ... */ }\n  goToHomePage(): void { /* ... */ }\n  updateProfile(details: UserDetails): void { /* ... */ }\n  getVersion(): string { /* ... */ }\n  // ...\n}\n\n```\n\n**Good:**\n\n```ts\nclass Dashboard {\n  disable(): void { /* ... */ }\n  enable(): void { /* ... */ }\n  getVersion(): string { /* ... */ }\n}\n\n// split the responsibilities by moving the remaining methods to other classes\n// ...\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### High cohesion and low coupling\n\nCohesion defines the degree to which class members are related to each other. Ideally, all fields within a class should be used by each method.\nWe then say that the class is *maximally cohesive*. In practice, this, however, is not always possible, nor even advisable. You should however prefer cohesion to be high.  \n\nCoupling refers to how related or dependent are two classes toward each other. Classes are said to be low coupled if changes in one of them don't affect the other one.  \n  \nGood software design has **high cohesion** and **low coupling**.\n\n**Bad:**\n\n```ts\nclass UserManager {\n  // Bad: each private variable is used by one or another group of methods.\n  // It makes clear evidence that the class is holding more than a single responsibility.\n  // If I need only to create the service to get the transactions for a user,\n  // I'm still forced to pass and instance of `emailSender`.\n  constructor(\n    private readonly db: Database,\n    private readonly emailSender: EmailSender) {\n  }\n\n  async getUser(id: number): Promise\u003cUser\u003e {\n    return await db.users.findOne({ id });\n  }\n\n  async getTransactions(userId: number): Promise\u003cTransaction[]\u003e {\n    return await db.transactions.find({ userId });\n  }\n\n  async sendGreeting(): Promise\u003cvoid\u003e {\n    await emailSender.send('Welcome!');\n  }\n\n  async sendNotification(text: string): Promise\u003cvoid\u003e {\n    await emailSender.send(text);\n  }\n\n  async sendNewsletter(): Promise\u003cvoid\u003e {\n    // ...\n  }\n}\n```\n\n**Good:**\n\n```ts\nclass UserService {\n  constructor(private readonly db: Database) {\n  }\n\n  async getUser(id: number): Promise\u003cUser\u003e {\n    return await this.db.users.findOne({ id });\n  }\n\n  async getTransactions(userId: number): Promise\u003cTransaction[]\u003e {\n    return await this.db.transactions.find({ userId });\n  }\n}\n\nclass UserNotifier {\n  constructor(private readonly emailSender: EmailSender) {\n  }\n\n  async sendGreeting(): Promise\u003cvoid\u003e {\n    await this.emailSender.send('Welcome!');\n  }\n\n  async sendNotification(text: string): Promise\u003cvoid\u003e {\n    await this.emailSender.send(text);\n  }\n\n  async sendNewsletter(): Promise\u003cvoid\u003e {\n    // ...\n  }\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Prefer composition over inheritance\n\nAs stated famously in [Design Patterns](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four, you should *prefer composition over inheritance* where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition. The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can.  \n  \nYou might be wondering then, \"when should I use inheritance?\" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:\n\n1. Your inheritance represents an \"is-a\" relationship and not a \"has-a\" relationship (Human-\u003eAnimal vs. User-\u003eUserDetails).\n\n2. You can reuse code from the base classes (Humans can move like all animals).\n\n3. You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).\n\n**Bad:**\n\n```ts\nclass Employee {\n  constructor(\n    private readonly name: string,\n    private readonly email: string) {\n  }\n\n  // ...\n}\n\n// Bad because Employees \"have\" tax data. EmployeeTaxData is not a type of Employee\nclass EmployeeTaxData extends Employee {\n  constructor(\n    name: string,\n    email: string,\n    private readonly ssn: string,\n    private readonly salary: number) {\n    super(name, email);\n  }\n\n  // ...\n}\n```\n\n**Good:**\n\n```ts\nclass Employee {\n  private taxData: EmployeeTaxData;\n\n  constructor(\n    private readonly name: string,\n    private readonly email: string) {\n  }\n\n  setTaxData(ssn: string, salary: number): Employee {\n    this.taxData = new EmployeeTaxData(ssn, salary);\n    return this;\n  }\n\n  // ...\n}\n\nclass EmployeeTaxData {\n  constructor(\n    public readonly ssn: string,\n    public readonly salary: number) {\n  }\n\n  // ...\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use method chaining\n\nThis pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose. For that reason, use method chaining and take a look at how clean your code will be.\n\n**Bad:**\n\n```ts\nclass QueryBuilder {\n  private collection: string;\n  private pageNumber: number = 1;\n  private itemsPerPage: number = 100;\n  private orderByFields: string[] = [];\n\n  from(collection: string): void {\n    this.collection = collection;\n  }\n\n  page(number: number, itemsPerPage: number = 100): void {\n    this.pageNumber = number;\n    this.itemsPerPage = itemsPerPage;\n  }\n\n  orderBy(...fields: string[]): void {\n    this.orderByFields = fields;\n  }\n\n  build(): Query {\n    // ...\n  }\n}\n\n// ...\n\nconst queryBuilder = new QueryBuilder();\nqueryBuilder.from('users');\nqueryBuilder.page(1, 100);\nqueryBuilder.orderBy('firstName', 'lastName');\n\nconst query = queryBuilder.build();\n```\n\n**Good:**\n\n```ts\nclass QueryBuilder {\n  private collection: string;\n  private pageNumber: number = 1;\n  private itemsPerPage: number = 100;\n  private orderByFields: string[] = [];\n\n  from(collection: string): this {\n    this.collection = collection;\n    return this;\n  }\n\n  page(number: number, itemsPerPage: number = 100): this {\n    this.pageNumber = number;\n    this.itemsPerPage = itemsPerPage;\n    return this;\n  }\n\n  orderBy(...fields: string[]): this {\n    this.orderByFields = fields;\n    return this;\n  }\n\n  build(): Query {\n    // ...\n  }\n}\n\n// ...\n\nconst query = new QueryBuilder()\n  .from('users')\n  .page(1, 100)\n  .orderBy('firstName', 'lastName')\n  .build();\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## SOLID\n\n### Single Responsibility Principle (SRP)\n\nAs stated in Clean Code, \"There should never be more than one reason for a class to change\". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of time you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.\n\n**Bad:**\n\n```ts\nclass UserSettings {\n  constructor(private readonly user: User) {\n  }\n\n  changeSettings(settings: UserSettings) {\n    if (this.verifyCredentials()) {\n      // ...\n    }\n  }\n\n  verifyCredentials() {\n    // ...\n  }\n}\n```\n\n**Good:**\n\n```ts\nclass UserAuth {\n  constructor(private readonly user: User) {\n  }\n\n  verifyCredentials() {\n    // ...\n  }\n}\n\n\nclass UserSettings {\n  private readonly auth: UserAuth;\n\n  constructor(private readonly user: User) {\n    this.auth = new UserAuth(user);\n  }\n\n  changeSettings(settings: UserSettings) {\n    if (this.auth.verifyCredentials()) {\n      // ...\n    }\n  }\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Open/Closed Principle (OCP)\n\nAs stated by Bertrand Meyer, \"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.\" What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.\n\n**Bad:**\n\n```ts\nclass AjaxAdapter extends Adapter {\n  constructor() {\n    super();\n  }\n\n  // ...\n}\n\nclass NodeAdapter extends Adapter {\n  constructor() {\n    super();\n  }\n\n  // ...\n}\n\nclass HttpRequester {\n  constructor(private readonly adapter: Adapter) {\n  }\n\n  async fetch\u003cT\u003e(url: string): Promise\u003cT\u003e {\n    if (this.adapter instanceof AjaxAdapter) {\n      const response = await makeAjaxCall\u003cT\u003e(url);\n      // transform response and return\n    } else if (this.adapter instanceof NodeAdapter) {\n      const response = await makeHttpCall\u003cT\u003e(url);\n      // transform response and return\n    }\n  }\n}\n\nfunction makeAjaxCall\u003cT\u003e(url: string): Promise\u003cT\u003e {\n  // request and return promise\n}\n\nfunction makeHttpCall\u003cT\u003e(url: string): Promise\u003cT\u003e {\n  // request and return promise\n}\n```\n\n**Good:**\n\n```ts\nabstract class Adapter {\n  abstract async request\u003cT\u003e(url: string): Promise\u003cT\u003e;\n\n  // code shared to subclasses ...\n}\n\nclass AjaxAdapter extends Adapter {\n  constructor() {\n    super();\n  }\n\n  async request\u003cT\u003e(url: string): Promise\u003cT\u003e{\n    // request and return promise\n  }\n\n  // ...\n}\n\nclass NodeAdapter extends Adapter {\n  constructor() {\n    super();\n  }\n\n  async request\u003cT\u003e(url: string): Promise\u003cT\u003e{\n    // request and return promise\n  }\n\n  // ...\n}\n\nclass HttpRequester {\n  constructor(private readonly adapter: Adapter) {\n  }\n\n  async fetch\u003cT\u003e(url: string): Promise\u003cT\u003e {\n    const response = await this.adapter.request\u003cT\u003e(url);\n    // transform response and return\n  }\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Liskov Substitution Principle (LSP)\n\nThis is a scary term for a very simple concept. It's formally defined as \"If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).\" That's an even scarier definition.  \n  \nThe best explanation for this is if you have a parent class and a child class, then the parent class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the \"is-a\" relationship via inheritance, you quickly get into trouble.\n\n**Bad:**\n\n```ts\nclass Rectangle {\n  constructor(\n    protected width: number = 0,\n    protected height: number = 0) {\n\n  }\n\n  setColor(color: string): this {\n    // ...\n  }\n\n  render(area: number) {\n    // ...\n  }\n\n  setWidth(width: number): this {\n    this.width = width;\n    return this;\n  }\n\n  setHeight(height: number): this {\n    this.height = height;\n    return this;\n  }\n\n  getArea(): number {\n    return this.width * this.height;\n  }\n}\n\nclass Square extends Rectangle {\n  setWidth(width: number): this {\n    this.width = width;\n    this.height = width;\n    return this;\n  }\n\n  setHeight(height: number): this {\n    this.width = height;\n    this.height = height;\n    return this;\n  }\n}\n\nfunction renderLargeRectangles(rectangles: Rectangle[]) {\n  rectangles.forEach((rectangle) =\u003e {\n    const area = rectangle\n      .setWidth(4)\n      .setHeight(5)\n      .getArea(); // BAD: Returns 25 for Square. Should be 20.\n    rectangle.render(area);\n  });\n}\n\nconst rectangles = [new Rectangle(), new Rectangle(), new Square()];\nrenderLargeRectangles(rectangles);\n```\n\n**Good:**\n\n```ts\nabstract class Shape {\n  setColor(color: string): this {\n    // ...\n  }\n\n  render(area: number) {\n    // ...\n  }\n\n  abstract getArea(): number;\n}\n\nclass Rectangle extends Shape {\n  constructor(\n    private readonly width = 0,\n    private readonly height = 0) {\n    super();\n  }\n\n  getArea(): number {\n    return this.width * this.height;\n  }\n}\n\nclass Square extends Shape {\n  constructor(private readonly length: number) {\n    super();\n  }\n\n  getArea(): number {\n    return this.length * this.length;\n  }\n}\n\nfunction renderLargeShapes(shapes: Shape[]) {\n  shapes.forEach((shape) =\u003e {\n    const area = shape.getArea();\n    shape.render(area);\n  });\n}\n\nconst shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];\nrenderLargeShapes(shapes);\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Interface Segregation Principle (ISP)\n\nISP states that \"Clients should not be forced to depend upon interfaces that they do not use.\". This principle is very much related to the Single Responsibility Principle.\nWhat it really means is that you should always design your abstractions in a way that the clients that are using the exposed methods do not get the whole pie instead. That also include imposing the clients with the burden of implementing methods that they don’t actually need.\n\n**Bad:**\n\n```ts\ninterface SmartPrinter {\n  print();\n  fax();\n  scan();\n}\n\nclass AllInOnePrinter implements SmartPrinter {\n  print() {\n    // ...\n  }  \n  \n  fax() {\n    // ...\n  }\n\n  scan() {\n    // ...\n  }\n}\n\nclass EconomicPrinter implements SmartPrinter {\n  print() {\n    // ...\n  }  \n  \n  fax() {\n    throw new Error('Fax not supported.');\n  }\n\n  scan() {\n    throw new Error('Scan not supported.');\n  }\n}\n```\n\n**Good:**\n\n```ts\ninterface Printer {\n  print();\n}\n\ninterface Fax {\n  fax();\n}\n\ninterface Scanner {\n  scan();\n}\n\nclass AllInOnePrinter implements Printer, Fax, Scanner {\n  print() {\n    // ...\n  }  \n  \n  fax() {\n    // ...\n  }\n\n  scan() {\n    // ...\n  }\n}\n\nclass EconomicPrinter implements Printer {\n  print() {\n    // ...\n  }\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Dependency Inversion Principle (DIP)\n\nThis principle states two essential things:\n\n1. High-level modules should not depend on low-level modules. Both should depend on abstractions.\n\n2. Abstractions should not depend upon details. Details should depend on abstractions.\n\nThis can be hard to understand at first, but if you've worked with Angular, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.  \n  \nDIP is usually achieved by a using an inversion of control (IoC) container. An example of a powerful IoC container for TypeScript is [InversifyJs](https://www.npmjs.com/package/inversify)\n\n**Bad:**\n\n```ts\nimport { readFile as readFileCb } from 'fs';\nimport { promisify } from 'util';\n\nconst readFile = promisify(readFileCb);\n\ntype ReportData = {\n  // ..\n}\n\nclass XmlFormatter {\n  parse\u003cT\u003e(content: string): T {\n    // Converts an XML string to an object T\n  }\n}\n\nclass ReportReader {\n\n  // BAD: We have created a dependency on a specific request implementation.\n  // We should just have ReportReader depend on a parse method: `parse`\n  private readonly formatter = new XmlFormatter();\n\n  async read(path: string): Promise\u003cReportData\u003e {\n    const text = await readFile(path, 'UTF8');\n    return this.formatter.parse\u003cReportData\u003e(text);\n  }\n}\n\n// ...\nconst reader = new ReportReader();\nconst report = await reader.read('report.xml');\n```\n\n**Good:**\n\n```ts\nimport { readFile as readFileCb } from 'fs';\nimport { promisify } from 'util';\n\nconst readFile = promisify(readFileCb);\n\ntype ReportData = {\n  // ..\n}\n\ninterface Formatter {\n  parse\u003cT\u003e(content: string): T;\n}\n\nclass XmlFormatter implements Formatter {\n  parse\u003cT\u003e(content: string): T {\n    // Converts an XML string to an object T\n  }\n}\n\n\nclass JsonFormatter implements Formatter {\n  parse\u003cT\u003e(content: string): T {\n    // Converts a JSON string to an object T\n  }\n}\n\nclass ReportReader {\n  constructor(private readonly formatter: Formatter) {\n  }\n\n  async read(path: string): Promise\u003cReportData\u003e {\n    const text = await readFile(path, 'UTF8');\n    return this.formatter.parse\u003cReportData\u003e(text);\n  }\n}\n\n// ...\nconst reader = new ReportReader(new XmlFormatter());\nconst report = await reader.read('report.xml');\n\n// or if we had to read a json report\nconst reader = new ReportReader(new JsonFormatter());\nconst report = await reader.read('report.json');\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Testing\n\nTesting is more important than shipping. If you have no tests or an inadequate amount, then every time you ship code you won't be sure that you didn't break anything.\nDeciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches)\nis how you achieve very high confidence and developer peace of mind. This means that in addition to having a great testing framework, you also need to use a good [coverage tool](https://github.com/gotwarlost/istanbul).\n\nThere's no excuse to not write tests. There are [plenty of good JS test frameworks](http://jstherightway.org/#testing-tools) with typings support for TypeScript, so find one that your team prefers. When you find one that works for your team, then aim to always write tests for every new feature/module you introduce. If your preferred method is Test Driven Development (TDD), that is great, but the main point is to just make sure you are reaching your coverage goals before launching any feature, or refactoring an existing one.  \n\n### The three laws of TDD\n\n1. You are not allowed to write any production code unless it is to make a failing unit test pass.\n\n2. You are not allowed to write any more of a unit test than is sufficient to fail, and; compilation failures are failures.\n\n3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.\n\n**[⬆ back to top](#table-of-contents)**\n\n### F.I.R.S.T. rules\n\nClean tests should follow the rules:\n\n- **Fast** tests should be fast because we want to run them frequently.\n\n- **Independent** tests should not depend on each other. They should provide same output whether run independently or all together in any order.\n\n- **Repeatable** tests should be repeatable in any environment and there should be no excuse for why they fail.\n\n- **Self-Validating** a test should answer with either *Passed* or *Failed*. You don't need to compare log files to answer if a test passed.\n\n- **Timely** unit tests should be written before the production code. If you write tests after the production code, you might find writing tests too hard.\n\n**[⬆ back to top](#table-of-contents)**\n\n### Single concept per test\n\nTests should also follow the *Single Responsibility Principle*. Make only one assert per unit test.\n\n**Bad:**\n\n```ts\nimport { assert } from 'chai';\n\ndescribe('AwesomeDate', () =\u003e {\n  it('handles date boundaries', () =\u003e {\n    let date: AwesomeDate;\n\n    date = new AwesomeDate('1/1/2015');\n    assert.equal('1/31/2015', date.addDays(30));\n\n    date = new AwesomeDate('2/1/2016');\n    assert.equal('2/29/2016', date.addDays(28));\n\n    date = new AwesomeDate('2/1/2015');\n    assert.equal('3/1/2015', date.addDays(28));\n  });\n});\n```\n\n**Good:**\n\n```ts\nimport { assert } from 'chai';\n\ndescribe('AwesomeDate', () =\u003e {\n  it('handles 30-day months', () =\u003e {\n    const date = new AwesomeDate('1/1/2015');\n    assert.equal('1/31/2015', date.addDays(30));\n  });\n\n  it('handles leap year', () =\u003e {\n    const date = new AwesomeDate('2/1/2016');\n    assert.equal('2/29/2016', date.addDays(28));\n  });\n\n  it('handles non-leap year', () =\u003e {\n    const date = new AwesomeDate('2/1/2015');\n    assert.equal('3/1/2015', date.addDays(28));\n  });\n});\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### The name of the test should reveal its intention\n\nWhen a test fails, its name is the first indication of what may have gone wrong.\n\n**Bad:**\n\n```ts\ndescribe('Calendar', () =\u003e {\n  it('2/29/2020', () =\u003e {\n    // ...\n  });\n\n  it('throws', () =\u003e {\n    // ...\n  });\n});\n```\n\n**Good:**\n\n```ts\ndescribe('Calendar', () =\u003e {\n  it('should handle leap year', () =\u003e {\n    // ...\n  });\n\n  it('should throw when format is invalid', () =\u003e {\n    // ...\n  });\n});\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Concurrency\n\n### Prefer promises vs callbacks\n\nCallbacks aren't clean, and they cause excessive amounts of nesting *(the callback hell)*.  \nThere are utilities that transform existing functions using the callback style to a version that returns promises\n(for Node.js see [`util.promisify`](https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original), for general purpose see [pify](https://www.npmjs.com/package/pify), [es6-promisify](https://www.npmjs.com/package/es6-promisify))\n\n**Bad:**\n\n```ts\nimport { get } from 'request';\nimport { writeFile } from 'fs';\n\nfunction downloadPage(url: string, saveTo: string, callback: (error: Error, content?: string) =\u003e void) {\n  get(url, (error, response) =\u003e {\n    if (error) {\n      callback(error);\n    } else {\n      writeFile(saveTo, response.body, (error) =\u003e {\n        if (error) {\n          callback(error);\n        } else {\n          callback(null, response.body);\n        }\n      });\n    }\n  });\n}\n\ndownloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html', (error, content) =\u003e {\n  if (error) {\n    console.error(error);\n  } else {\n    console.log(content);\n  }\n});\n```\n\n**Good:**\n\n```ts\nimport { get } from 'request';\nimport { writeFile } from 'fs';\nimport { promisify } from 'util';\n\nconst write = promisify(writeFile);\n\nfunction downloadPage(url: string, saveTo: string): Promise\u003cstring\u003e {\n  return get(url)\n    .then(response =\u003e write(saveTo, response));\n}\n\ndownloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html')\n  .then(content =\u003e console.log(content))\n  .catch(error =\u003e console.error(error));  \n```\n\nPromises supports a few helper methods that help make code more concise:  \n\n| Pattern                  | Description                                |  \n| ------------------------ | -----------------------------------------  |  \n| `Promise.resolve(value)` | Convert a value into a resolved promise.   |  \n| `Promise.reject(error)`  | Convert an error into a rejected promise.  |  \n| `Promise.all(promises)`  | Returns a new promise which is fulfilled with an array of fulfillment values for the passed promises or rejects with the reason of the first promise that rejects. |\n| `Promise.race(promises)`| Returns a new promise which is fulfilled/rejected with the result/error of the first settled promise from the array of passed promises. |\n\n`Promise.all` is especially useful when there is a need to run tasks in parallel. `Promise.race` makes it easier to implement things like timeouts for promises.\n\n**[⬆ back to top](#table-of-contents)**\n\n### Async/Await are even cleaner than Promises\n\nWith `async`/`await` syntax you can write code that is far cleaner and more understandable than chained promises. Within a function prefixed with `async` keyword, you have a way to tell the JavaScript runtime to pause the execution of code on the `await` keyword (when used on a promise).\n\n**Bad:**\n\n```ts\nimport { get } from 'request';\nimport { writeFile } from 'fs';\nimport { promisify } from 'util';\n\nconst write = util.promisify(writeFile);\n\nfunction downloadPage(url: string, saveTo: string): Promise\u003cstring\u003e {\n  return get(url).then(response =\u003e write(saveTo, response));\n}\n\ndownloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html')\n  .then(content =\u003e console.log(content))\n  .catch(error =\u003e console.error(error));  \n```\n\n**Good:**\n\n```ts\nimport { get } from 'request';\nimport { writeFile } from 'fs';\nimport { promisify } from 'util';\n\nconst write = promisify(writeFile);\n\nasync function downloadPage(url: string): Promise\u003cstring\u003e {\n  const response = await get(url);\n  return response;\n}\n\n// somewhere in an async function\ntry {\n  const content = await downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');\n  await write('article.html', content);\n  console.log(content);\n} catch (error) {\n  console.error(error);\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Error Handling\n\nThrown errors are a good thing! They mean the runtime has successfully identified when something in your program has gone wrong and it's letting you know by stopping function\nexecution on the current stack, killing the process (in Node), and notifying you in the console with a stack trace.\n\n### Always use Error for throwing or rejecting\n\nJavaScript as well as TypeScript allow you to `throw` any object. A Promise can also be rejected with any reason object.  \nIt is advisable to use the `throw` syntax with an `Error` type. This is because your error might be caught in higher level code with a `catch` syntax.\nIt would be very confusing to catch a string message there and would make\n[debugging more painful](https://basarat.gitbook.io/typescript/type-system/exceptions#always-use-error).  \nFor the same reason you should reject promises with `Error` types.\n\n**Bad:**\n\n```ts\nfunction calculateTotal(items: Item[]): number {\n  throw 'Not implemented.';\n}\n\nfunction get(): Promise\u003cItem[]\u003e {\n  return Promise.reject('Not implemented.');\n}\n```\n\n**Good:**\n\n```ts\nfunction calculateTotal(items: Item[]): number {\n  throw new Error('Not implemented.');\n}\n\nfunction get(): Promise\u003cItem[]\u003e {\n  return Promise.reject(new Error('Not implemented.'));\n}\n\n// or equivalent to:\n\nasync function get(): Promise\u003cItem[]\u003e {\n  throw new Error('Not implemented.');\n}\n```\n\nThe benefit of using `Error` types is that it is supported by the syntax `try/catch/finally` and implicitly all errors have the `stack` property which\nis very powerful for debugging.  \nThere are also other alternatives, not to use the `throw` syntax and instead always return custom error objects. TypeScript makes this even easier.\nConsider the following example:\n\n```ts\ntype Result\u003cR\u003e = { isError: false, value: R };\ntype Failure\u003cE\u003e = { isError: true, error: E };\ntype Failable\u003cR, E\u003e = Result\u003cR\u003e | Failure\u003cE\u003e;\n\nfunction calculateTotal(items: Item[]): Failable\u003cnumber, 'empty'\u003e {\n  if (items.length === 0) {\n    return { isError: true, error: 'empty' };\n  }\n\n  // ...\n  return { isError: false, value: 42 };\n}\n```\n\nFor the detailed explanation of this idea refer to the [original post](https://medium.com/@dhruvrajvanshi/making-exceptions-type-safe-in-typescript-c4d200ee78e9).\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't ignore caught errors\n\nDoing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Logging the error to the console (`console.log`) isn't much better as often it can get lost in a sea of things printed to the console. If you wrap any bit of code in a `try/catch` it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs.\n\n**Bad:**\n\n```ts\ntry {\n  functionThatMightThrow();\n} catch (error) {\n  console.log(error);\n}\n\n// or even worse\n\ntry {\n  functionThatMightThrow();\n} catch (error) {\n  // ignore error\n}\n```\n\n**Good:**\n\n```ts\nimport { logger } from './logging'\n\ntry {\n  functionThatMightThrow();\n} catch (error) {\n  logger.log(error);\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't ignore rejected promises\n\nFor the same reason you shouldn't ignore caught errors from `try/catch`.\n\n**Bad:**\n\n```ts\ngetUser()\n  .then((user: User) =\u003e {\n    return sendEmail(user.email, 'Welcome!');\n  })\n  .catch((error) =\u003e {\n    console.log(error);\n  });\n```\n\n**Good:**\n\n```ts\nimport { logger } from './logging'\n\ngetUser()\n  .then((user: User) =\u003e {\n    return sendEmail(user.email, 'Welcome!');\n  })\n  .catch((error) =\u003e {\n    logger.log(error);\n  });\n\n// or using the async/await syntax:\n\ntry {\n  const user = await getUser();\n  await sendEmail(user.email, 'Welcome!');\n} catch (error) {\n  logger.log(error);\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Formatting\n\nFormatting is subjective. Like many rules herein, there is no hard and fast rule that you must follow. The main point is *DO NOT ARGUE* over formatting. There are tons of tools to automate this. Use one! It's a waste of time and money for engineers to argue over formatting. The general rule to follow is *keep consistent formatting rules*.  \n\nFor TypeScript there is a powerful tool called [ESLint](https://typescript-eslint.io/). It's a static analysis tool that can help you improve dramatically the readability and maintainability of your code. There are ready to use ESLint configurations that you can reference in your projects:\n\n- [ESLint Config Airbnb](https://www.npmjs.com/package/eslint-config-airbnb-typescript) - Airbnb style guide\n\n- [ESLint Base Style Config](https://www.npmjs.com/package/eslint-plugin-base-style-config) - a Set of Essential ESLint rules for JS, TS and React\n\n- [ESLint + Prettier](https://www.npmjs.com/package/eslint-config-prettier) - lint rules for [Prettier](https://github.com/prettier/prettier) code formatter\n\nRefer also to this great [TypeScript StyleGuide and Coding Conventions](https://basarat.gitbook.io/typescript/styleguide) source.\n\n### Migrating from TSLint to ESLint\n\nIf you are looking for help in migrating from TSLint to ESLint, you can check out this project: \u003chttps://github.com/typescript-eslint/tslint-to-eslint-config\u003e\n\n### Use consistent capitalization\n\nCapitalization tells you a lot about your variables, functions, etc. These rules are subjective, so your team can choose whatever they want. The point is, no matter what you all choose, just *be consistent*.\n\n**Bad:**\n\n```ts\nconst DAYS_IN_WEEK = 7;\nconst daysInMonth = 30;\n\nconst songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];\nconst Artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];\n\nfunction eraseDatabase() {}\nfunction restore_database() {}\n\ntype animal = { /* ... */ }\ntype Container = { /* ... */ }\n```\n\n**Good:**\n\n```ts\nconst DAYS_IN_WEEK = 7;\nconst DAYS_IN_MONTH = 30;\n\nconst SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];\nconst ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles'];\n\nconst discography = getArtistDiscography('ACDC');\nconst beatlesSongs = SONGS.filter((song) =\u003e isBeatlesSong(song));\n\nfunction eraseDatabase() {}\nfunction restoreDatabase() {}\n\ntype Animal = { /* ... */ }\ntype Container = { /* ... */ }\n```\n\nPrefer using `PascalCase` for class, interface, type and namespace names.  \nPrefer using `camelCase` for variables, functions and class members.\nPrefer using capitalized `SNAKE_CASE` for constants.\n\n**[⬆ back to top](#table-of-contents)**\n\n### Function callers and callees should be close\n\nIf a function calls another, keep those functions vertically close in the source file. Ideally, keep the caller right above the callee.\nWe tend to read code from top-to-bottom, like a newspaper. Because of this, make your code read that way.\n\n**Bad:**\n\n```ts\nclass PerformanceReview {\n  constructor(private readonly employee: Employee) {\n  }\n\n  private lookupPeers() {\n    return db.lookup(this.employee.id, 'peers');\n  }\n\n  private lookupManager() {\n    return db.lookup(this.employee, 'manager');\n  }\n\n  private getPeerReviews() {\n    const peers = this.lookupPeers();\n    // ...\n  }\n\n  review() {\n    this.getPeerReviews();\n    this.getManagerReview();\n    this.getSelfReview();\n\n    // ...\n  }\n\n  private getManagerReview() {\n    const manager = this.lookupManager();\n  }\n\n  private getSelfReview() {\n    // ...\n  }\n}\n\nconst review = new PerformanceReview(employee);\nreview.review();\n```\n\n**Good:**\n\n```ts\nclass PerformanceReview {\n  constructor(private readonly employee: Employee) {\n  }\n\n  review() {\n    this.getPeerReviews();\n    this.getManagerReview();\n    this.getSelfReview();\n\n    // ...\n  }\n\n  private getPeerReviews() {\n    const peers = this.lookupPeers();\n    // ...\n  }\n\n  private lookupPeers() {\n    return db.lookup(this.employee.id, 'peers');\n  }\n\n  private getManagerReview() {\n    const manager = this.lookupManager();\n  }\n\n  private lookupManager() {\n    return db.lookup(this.employee, 'manager');\n  }\n\n  private getSelfReview() {\n    // ...\n  }\n}\n\nconst review = new PerformanceReview(employee);\nreview.review();\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Organize imports\n\nWith clean and easy to read import statements you can quickly see the dependencies of current code. Make sure you apply following good practices for `import` statements:\n\n- Import statements should be alphabetized and grouped.\n- Unused imports should be removed.\n- Named imports must be alphabetized (i.e. `import {A, B, C} from 'foo';`)\n- Import sources must be alphabetized within groups, i.e.: `import * as foo from 'a'; import * as bar from 'b';`\n- Prefer using `import type` instead of `import` when importing only types from a file to avoid dependency cycles, as these imports are erased at runtime\n- Groups of imports are delineated by blank lines.\n- Groups must respect following order:\n  - Polyfills (i.e. `import 'reflect-metadata';`)\n  - Node builtin modules (i.e. `import fs from 'fs';`)\n  - external modules (i.e. `import { query } from 'itiriri';`)\n  - internal modules (i.e `import { UserService } from 'src/services/userService';`)\n  - modules from a parent directory (i.e. `import foo from '../foo'; import qux from '../../foo/qux';`)\n  - modules from the same or a sibling's directory (i.e. `import bar from './bar'; import baz from './bar/baz';`)\n\n**Bad:**\n\n```ts\nimport { TypeDefinition } from '../types/typeDefinition';\nimport { AttributeTypes } from '../model/attribute';\nimport { Customer, Credentials } from '../model/types';\nimport { ApiCredentials, Adapters } from './common/api/authorization';\nimport fs from 'fs';\nimport { ConfigPlugin } from './plugins/config/configPlugin';\nimport { BindingScopeEnum, Container } from 'inversify';\nimport 'reflect-metadata';\n```\n\n**Good:**\n\n```ts\nimport 'reflect-metadata';\n\nimport fs from 'fs';\nimport { BindingScopeEnum, Container } from 'inversify';\n\nimport { AttributeTypes } from '../model/attribute';\nimport { TypeDefinition } from '../types/typeDefinition';\nimport type { Customer, Credentials } from '../model/types';\n\nimport { ApiCredentials, Adapters } from './common/api/authorization';\nimport { ConfigPlugin } from './plugins/config/configPlugin';\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Use typescript aliases\n\nCreate prettier imports by defining the paths and baseUrl properties in the compilerOptions section in the `tsconfig.json`\n\nThis will avoid long relative paths when doing imports.\n\n**Bad:**\n\n```ts\nimport { UserService } from '../../../services/UserService';\n```\n\n**Good:**\n\n```ts\nimport { UserService } from '@services/UserService';\n```\n\n```js\n// tsconfig.json\n...\n  \"compilerOptions\": {\n    ...\n    \"baseUrl\": \"src\",\n    \"paths\": {\n      \"@services\": [\"services/*\"]\n    }\n    ...\n  }\n...\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Comments\n\nThe use of a comments is an indication of failure to express without them. Code should be the only source of truth.\n  \n\u003e Don’t comment bad code—rewrite it.  \n\u003e — *Brian W. Kernighan and P. J. Plaugher*\n\n### Prefer self explanatory code instead of comments\n\nComments are an apology, not a requirement. Good code *mostly* documents itself.\n\n**Bad:**\n\n```ts\n// Check if subscription is active.\nif (subscription.endDate \u003e Date.now) {  }\n```\n\n**Good:**\n\n```ts\nconst isSubscriptionActive = subscription.endDate \u003e Date.now;\nif (isSubscriptionActive) { /* ... */ }\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't leave commented out code in your codebase\n\nVersion control exists for a reason. Leave old code in your history.\n\n**Bad:**\n\n```ts\ntype User = {\n  name: string;\n  email: string;\n  // age: number;\n  // jobPosition: string;\n}\n```\n\n**Good:**\n\n```ts\ntype User = {\n  name: string;\n  email: string;\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Don't have journal comments\n\nRemember, use version control! There's no need for dead code, commented code, and especially journal comments. Use `git log` to get history!\n\n**Bad:**\n\n```ts\n/**\n * 2016-12-20: Removed monads, didn't understand them (RM)\n * 2016-10-01: Improved using special monads (JP)\n * 2016-02-03: Added type-checking (LI)\n * 2015-03-14: Implemented combine (JR)\n */\nfunction combine(a: number, b: number): number {\n  return a + b;\n}\n```\n\n**Good:**\n\n```ts\nfunction combine(a: number, b: number): number {\n  return a + b;\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid positional markers\n\nThey usually just add noise. Let the functions and variable names along with the proper indentation and formatting give the visual structure to your code.  \nMost IDE support code folding feature that allows you to collapse/expand blocks of code (see Visual Studio Code [folding regions](https://code.visualstudio.com/updates/v1_17#_folding-regions)).\n\n**Bad:**\n\n```ts\n////////////////////////////////////////////////////////////////////////////////\n// Client class\n////////////////////////////////////////////////////////////////////////////////\nclass Client {\n  id: number;\n  name: string;\n  address: Address;\n  contact: Contact;\n\n  ////////////////////////////////////////////////////////////////////////////////\n  // public methods\n  ////////////////////////////////////////////////////////////////////////////////\n  public describe(): string {\n    // ...\n  }\n\n  ////////////////////////////////////////////////////////////////////////////////\n  // private methods\n  ////////////////////////////////////////////////////////////////////////////////\n  private describeAddress(): string {\n    // ...\n  }\n\n  private describeContact(): string {\n    // ...\n  }\n};\n```\n\n**Good:**\n\n```ts\nclass Client {\n  id: number;\n  name: string;\n  address: Address;\n  contact: Contact;\n\n  public describe(): string {\n    // ...\n  }\n\n  private describeAddress(): string {\n    // ...\n  }\n\n  private describeContact(): string {\n    // ...\n  }\n};\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n### TODO comments\n\nWhen you find yourself that you need to leave notes in the code for some later improvements,\ndo that using `// TODO` comments. Most IDE have special support for those kinds of comments so that\nyou can quickly go over the entire list of todos.  \n\nKeep in mind however that a *TODO* comment is not an excuse for bad code. \n\n**Bad:**\n\n```ts\nfunction getActiveSubscriptions(): Promise\u003cSubscription[]\u003e {\n  // ensure `dueDate` is indexed.\n  return db.subscriptions.find({ dueDate: { $lte: new Date() } });\n}\n```\n\n**Good:**\n\n```ts\nfunction getActiveSubscriptions(): Promise\u003cSubscription[]\u003e {\n  // TODO: ensure `dueDate` is indexed.\n  return db.subscriptions.find({ dueDate: { $lte: new Date() } });\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Translations\n\nThis is also available in other languages:\n- ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Brazilian Portuguese**: [vitorfreitas/clean-code-typescript](https://github.com/vitorfreitas/clean-code-typescript)\n- ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese**: \n  - [beginor/clean-code-typescript](https://github.com/beginor/clean-code-typescript)\n  - [pipiliang/clean-code-typescript](https://github.com/pipiliang/clean-code-typescript)\n- ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **French**: [ralflorent/clean-code-typescript](https://github.com/ralflorent/clean-code-typescript)\n- ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **German**: [mheob/clean-code-typescript](https://github.com/mheob/clean-code-typescript)\n- ![ja](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **Japanese**: [MSakamaki/clean-code-typescript](https://github.com/MSakamaki/clean-code-typescript)\n- ![ko](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Korean**: [738/clean-code-typescript](https://github.com/738/clean-code-typescript)\n- ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: [Real001/clean-code-typescript](https://github.com/Real001/clean-code-typescript)\n- ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png) **Spanish**: [3xp1o1t/clean-code-typescript](https://github.com/3xp1o1t/clean-code-typescript)\n- ![tr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Turkey.png) **Turkish**: [ozanhonamlioglu/clean-code-typescript](https://github.com/ozanhonamlioglu/clean-code-typescript)\n- ![vi](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png) **Vietnamese**: [hoangsetup/clean-code-typescript](https://github.com/hoangsetup/clean-code-typescript)\n\nReferences will be added once translations are completed.  \nCheck this [discussion](https://github.com/labs42io/clean-code-typescript/issues/15) for more details and progress.\nYou can make an indispensable contribution to *Clean Code* community by translating this to your language.\n\n**[⬆ back to top](#table-of-contents)**\n","funding_links":[],"categories":["Getting Started with (Awesome) TypeScript","TypeScript","其它代码整洁之道列表","Documentation / Guides / Exercises / Boilerplates","Table of Contents","目录","📚 Books","Uncategorized","Typescript","Learning Resources","Coding"],"sub_categories":["Awesome TypeScript Essential Resources","Typescript / Javascript","构建工具/预编译","Uncategorized","Graph Theory","Server-rendered React"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flabs42io%2Fclean-code-typescript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flabs42io%2Fclean-code-typescript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flabs42io%2Fclean-code-typescript/lists"}