[
  {
    "path": ".all-contributorsrc",
    "content": "{\n  \"files\": [\n    \"CONTRIBUTORS.md\",\n    \"README.md\"\n  ],\n  \"imageSize\": 100,\n  \"commit\": true,\n  \"commitConvention\": \"angular\",\n  \"contributors\": [\n    {\n      \"login\": \"ferdaber\",\n      \"name\": \"Ferdy Budhidharma\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/12239873?v=4\",\n      \"profile\": \"https://github.com/ferdaber\",\n      \"contributions\": [\n        \"review\",\n        \"maintenance\",\n        \"content\"\n      ]\n    },\n    {\n      \"login\": \"sw-yx\",\n      \"name\": \"swyx\",\n      \"avatar_url\": \"https://avatars1.githubusercontent.com/u/6764957?v=4\",\n      \"profile\": \"https://twitter.com/swyx\",\n      \"contributions\": [\n        \"ideas\",\n        \"review\",\n        \"maintenance\",\n        \"content\",\n        \"question\"\n      ]\n    },\n    {\n      \"login\": \"eps1lon\",\n      \"name\": \"Sebastian Silbermann\",\n      \"avatar_url\": \"https://avatars3.githubusercontent.com/u/12292047?v=4\",\n      \"profile\": \"https://github.com/eps1lon\",\n      \"contributions\": [\n        \"review\",\n        \"maintenance\",\n        \"content\"\n      ]\n    },\n    {\n      \"login\": \"Attrash-Islam\",\n      \"name\": \"Islam Attrash\",\n      \"avatar_url\": \"https://avatars0.githubusercontent.com/u/7091543?v=4\",\n      \"profile\": \"https://www.linkedin.com/in/islam-attrash-46703a94/\",\n      \"contributions\": [\n        \"maintenance\",\n        \"content\"\n      ]\n    },\n    {\n      \"login\": \"stephenkoo\",\n      \"name\": \"Stephen Koo\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/18624246?v=4\",\n      \"profile\": \"https://stephenkoo.github.io/\",\n      \"contributions\": [\n        \"question\",\n        \"example\"\n      ]\n    },\n    {\n      \"login\": \"andreasgruenh\",\n      \"name\": \"Andreas\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/12122390?v=4\",\n      \"profile\": \"https://github.com/andreasgruenh\",\n      \"contributions\": [\n        \"code\",\n        \"doc\",\n        \"infra\"\n      ]\n    },\n    {\n      \"login\": \"arvindcheenu\",\n      \"name\": \"Arvind Srinivasan\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/13925213?v=4\",\n      \"profile\": \"https://github.com/arvindcheenu\",\n      \"contributions\": [\n        \"code\",\n        \"content\",\n        \"doc\",\n        \"maintenance\"\n      ]\n    },\n    {\n      \"login\": \"williamrjribeiro\",\n      \"name\": \"William R. J. Ribeiro\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/1503499?v=4\",\n      \"profile\": \"http://www.williamrjribeiro.com\",\n      \"contributions\": [\n        \"ideas\"\n      ]\n    },\n    {\n      \"login\": \"alexandrudanpop\",\n      \"name\": \"Alexandru-Dan Pop\",\n      \"avatar_url\": \"https://avatars0.githubusercontent.com/u/15979292?v=4\",\n      \"profile\": \"https://alexandrudanpop.dev/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"mastorm\",\n      \"name\": \"Mathias Storm\",\n      \"avatar_url\": \"https://avatars1.githubusercontent.com/u/10759336?v=4\",\n      \"profile\": \"https://github.com/mastorm\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"dance2die\",\n      \"name\": \"Sung M. Kim\",\n      \"avatar_url\": \"https://avatars1.githubusercontent.com/u/8465237?v=4\",\n      \"profile\": \"https://twitter.com/dance2die\",\n      \"contributions\": [\n        \"doc\",\n        \"ideas\"\n      ]\n    },\n    {\n      \"login\": \"ryota-murakami\",\n      \"name\": \"Ryota Murakami\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/5501268?v=4\",\n      \"profile\": \"https://ryota-murakami.github.io/\",\n      \"contributions\": [\n        \"example\",\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"arpi17\",\n      \"name\": \"Árpád Illyés\",\n      \"avatar_url\": \"https://avatars1.githubusercontent.com/u/13800404?v=4\",\n      \"profile\": \"https://github.com/arpi17\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"xamgore\",\n      \"name\": \"Igor Strebezhev\",\n      \"avatar_url\": \"https://avatars3.githubusercontent.com/u/4586392?v=4\",\n      \"profile\": \"https://twitter.com/xamgore\",\n      \"contributions\": [\n        \"ideas\",\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"dwjohnston\",\n      \"name\": \"David Johnston\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/2467377?v=4\",\n      \"profile\": \"https://geoplanets.io\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"kripod\",\n      \"name\": \"Kristóf Poduszló\",\n      \"avatar_url\": \"https://avatars3.githubusercontent.com/u/14854048?v=4\",\n      \"profile\": \"https://github.com/kripod\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"glaschu1\",\n      \"name\": \"james glasgow\",\n      \"avatar_url\": \"https://avatars3.githubusercontent.com/u/10838852?v=4\",\n      \"profile\": \"http://www.novusstudio.com/\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"Winner95\",\n      \"name\": \"Ivan\",\n      \"avatar_url\": \"https://avatars0.githubusercontent.com/u/13730032?v=4\",\n      \"profile\": \"https://www.linkedin.com/in/iigrekov/\",\n      \"contributions\": [\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"selrond\",\n      \"name\": \"Sebastian Andil\",\n      \"avatar_url\": \"https://avatars1.githubusercontent.com/u/6603389?v=4\",\n      \"profile\": \"http://sebastianandil.com\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"adnanhusain15\",\n      \"name\": \"Adnan Husain\",\n      \"avatar_url\": \"https://avatars2.githubusercontent.com/u/36721076?v=4\",\n      \"profile\": \"https://github.com/adnanhusain15\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"artola\",\n      \"name\": \"martin\",\n      \"avatar_url\": \"https://avatars0.githubusercontent.com/u/11500763?v=4\",\n      \"profile\": \"https://github.com/artola\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"filiptammergard\",\n      \"name\": \"Filip Tammergård\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/44197016?v=4\",\n      \"profile\": \"https://tammergard.se\",\n      \"contributions\": [\n        \"doc\",\n        \"code\"\n      ]\n    },\n    {\n      \"login\": \"jsjoeio\",\n      \"name\": \"Joe Previte\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/3806031?v=4\",\n      \"profile\": \"https://englishbyte.com\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    },\n    {\n      \"login\": \"sasirura\",\n      \"name\": \"Sasiru Ravihansa\",\n      \"avatar_url\": \"https://avatars.githubusercontent.com/u/42542164?v=4\",\n      \"profile\": \"https://github.com/sasirura\",\n      \"contributions\": [\n        \"doc\"\n      ]\n    }\n  ],\n  \"contributorsPerLine\": 7,\n  \"projectName\": \"react\",\n  \"projectOwner\": \"typescript-cheatsheets\",\n  \"repoType\": \"github\",\n  \"repoHost\": \"https://github.com\",\n  \"skipCi\": true,\n  \"commitType\": \"docs\"\n}\n"
  },
  {
    "path": ".dockerignore",
    "content": "*/node_modules\n*.log\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/advanced-cheatsheet.md",
    "content": "---\nname: Advanced Cheatsheet\nabout: Report Issue/Suggest an idea for Advanced Cheatsheet\ntitle: \"[Advanced] ISSUE_TITLE_HERE\"\nlabels: ADVANCED\nassignees: \"\"\n---\n\n**What cheatsheet is this about? (if applicable)**\n\nAdvanced cheatsheet\n\n**What's your issue or idea?**\n\n_Write here_\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/basic-cheatsheet.md",
    "content": "---\nname: Basic Cheatsheet\nabout: Report Issue/Suggest an idea for Basic Cheatsheet\ntitle: \"[Basic] ISSUE_TITLE_HERE\"\nlabels: BASIC\nassignees: sw-yx\n---\n\n**What cheatsheet is this about? (if applicable)**\n\nBasic cheatsheet\n\n**What's your issue or idea?**\n\n_Write here_\n\n**(If applicable) Reproduction of issue in TypeScript Playground**\n\n_[start with the basic TS + React template](https://www.typescriptlang.org/play/?jsx=2&esModuleInterop=true&q=222#example/typescript-with-react)_\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/general-react-ts-question.md",
    "content": "---\nname: General React+TS Question\nabout: Questions are welcome! We want to know and solve your pain points.\ntitle: \"[Question] QUESTION_TITLE_HERE\"\nlabels: good first issue\nassignees: sw-yx\n---\n\n**(If applicable) Reproduction of issue in TypeScript Playground**\n\n_[start with the basic TS + React template](https://www.typescriptlang.org/play/?jsx=2&esModuleInterop=true&q=222#example/typescript-with-react)_\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/hoc-cheatsheet.md",
    "content": "---\nname: HOC Cheatsheet\nabout: Report Issue/Suggest an idea for HOC Cheatsheet\ntitle: \"[HOC] ISSUE_TITLE_HERE\"\nlabels: HOC\nassignees: \"\"\n---\n\n**What cheatsheet is this about? (if applicable)**\n\nHOC cheatsheet\n\n**What's your issue or idea?**\n\n_Write here_\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/migrating-cheatsheet.md",
    "content": "---\nname: Migrating Cheatsheet\nabout: Report Issue/Suggest an idea for Migrating Cheatsheet\ntitle: \"[Migrating] ISSUE_TITLE_HERE\"\nlabels: MIGRATING\nassignees: \"\"\n---\n\n**What cheatsheet is this about? (if applicable)**\n\nMigrating cheatsheet\n\n**What's your issue or idea?**\n\n_Write here_\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "Thanks for contributing!\n\n- **If you are making a significant PR**, please make sure there is an open issue first\n- **If you're just fixing typos or adding small notes**, a brief explanation of why you'd like to add it would be nice :)\n\n**If you are contributing to README.md, DON'T**. README.md is auto-generated. Please just make edits to the source inside of `/docs/basic`. _Sorry, we get that it is a slight pain._\n"
  },
  {
    "path": ".github/stale.yml",
    "content": "# Number of days of inactivity before an issue becomes stale\ndaysUntilStale: 60\n# Number of days of inactivity before a stale issue is closed\ndaysUntilClose: 7\n# Issues with these labels will never be considered stale\nexemptLabels:\n  - pinned\n  - security\n# Label to use when marking an issue as stale\nstaleLabel: wontfix\n# Comment to post when marking an issue as stale. Set to `false` to disable\nmarkComment: >\n  This issue has been automatically marked as stale because it has not had\n  recent activity. It will be closed if no further activity occurs. Thank you\n  for your contributions!\n# Comment to post when closing a stale issue. Set to `false` to disable\ncloseComment: false\n"
  },
  {
    "path": ".github/workflows/main.yml",
    "content": "name: CI\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\njobs:\n  files-up-to-date:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout commit\n        uses: actions/checkout@v4\n\n      - name: Setup node\n        uses: actions/setup-node@v4\n        with:\n          node-version-file: \".nvmrc\"\n          cache: yarn\n\n      - name: Install dependencies\n        run: yarn install --frozen-lockfile\n\n      - name: \"`yarn format` changes committed?\"\n        run: yarn format:check\n\n      - name: \"`yarn gen-readme` changes committed?\"\n        run: |\n          yarn gen-readme\n          git diff --exit-code\n"
  },
  {
    "path": ".github/workflows/mlc_config.json",
    "content": "{\n  \"aliveStatusCodes\": [200, 429]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n.env.test\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# Idea / Jetbrains IDE\n.idea\n\n# yarn v2\n.yarn/cache\n.yarn/unplugged\n.yarn/build-state.yml\n.pnp.*\n\n# Miscellaneous\n.history\n.DS_Store\n\n# Docusaurus files\nwebsite/build\nwebsite/.docusaurus\nwebsite/.cache-loader\n\n# copy of contributors for the website\nwebsite/src/pages/contributing.md\nwebsite/src/pages/contributors.md\n\n# Local Netlify folder\n.netlify\n\n# Lock-files\npackage-lock.json\nyarn.lock\n"
  },
  {
    "path": ".husky/pre-commit",
    "content": "#!/bin/sh\n. \"$(dirname \"$0\")/_/husky.sh\"\n\nyarn pretty-quick --staged\n"
  },
  {
    "path": ".nvmrc",
    "content": "20.x\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Let's Contribute Together! 🚀\n\nWe appreciate your interest in contributing to this project. Here are some core principles and a simplified project structure to make your contribution process more efficient and effective:\n\n## 📋 Core Principles\n\n1. **We're All About Cheatsheets**: Our main goal is to provide concise and easy-to-use cheatsheets. All code examples should be simple, easily searchable, and ready for copy-and-paste.\n\n2. **Collapsible Explanations**: Keep explanations short and sweet, limited to 1-2 sentences. For more in-depth explanations, use `details` tags to provide additional context.\n\n3. **React + TypeScript Only**: We focus on React and TypeScript. React's ecosystem is vast, so we won't cover everything. If you think there's a need, consider maintaining separate lists for specialized topics, like React + Apollo GraphQL. We also don't aim to convince people to use TypeScript; we're here to assist those who have already chosen to use it.\n\n4. **Add TypeScript Playground Links**: For code examples longer than four lines, include a link to the TypeScript Playground. Use the default TypeScript Playground options for the best experience.\n\nYour contributions will help countless developers, including your future self! 🙌\n\n## 📁 Project Structure\n\n- **Content in `/docs`**: All the content resides here.\n  - The content in `/docs/basic` is compiled into `README.md` to ensure that it's easy to read on GitHub.\n- **`/website` Folder**: This part consumes the content in `/docs`. It's a Docusaurus 2 site and includes Algolia search. A big thanks to both the Docusaurus and Algolia teams for their support!\n\nThe website is deployed on Netlify, under swyx's personal account.\n\nTo run the docsite locally, follow these steps:\n\n```bash\nyarn # Install dependencies\n## Ensure dependencies are also installed in /website\ncd website && yarn start\n```\n\nHere's an example of the expected output when the development server starts successfully:\n\n```\nyarn run v1.22.4\nwarning package.json: No license field\n$ docusaurus start\nStarting the development server...\n\n✔ Client\n  Compiled successfully in 9.61s\n\nℹ ｢wds｣: Project is running at http://localhost:3000/\nℹ ｢wds｣: webpack output is served from /\nℹ ｢wds｣: Content not from webpack is served from /Users/wanshawn/Work/react-typescript-cheatsheet/website\nℹ ｢wds｣: 404s will fallback to /index.html\n\n✔ Client\n  Compiled successfully in 116.41ms\n```\n\nLet's work together to enhance this resource and make it even more valuable to the developer community! 🌟👩‍💻👨‍💻\n"
  },
  {
    "path": "CONTRIBUTORS.md",
    "content": "## Contributors\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n  <tbody>\n    <tr>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/ferdaber\"><img src=\"https://avatars2.githubusercontent.com/u/12239873?v=4?s=100\" width=\"100px;\" alt=\"Ferdy Budhidharma\"/><br /><sub><b>Ferdy Budhidharma</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/pulls?q=is%3Apr+reviewed-by%3Aferdaber\" title=\"Reviewed Pull Requests\">👀</a> <a href=\"#maintenance-ferdaber\" title=\"Maintenance\">🚧</a> <a href=\"#content-ferdaber\" title=\"Content\">🖋</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://twitter.com/swyx\"><img src=\"https://avatars1.githubusercontent.com/u/6764957?v=4?s=100\" width=\"100px;\" alt=\"swyx\"/><br /><sub><b>swyx</b></sub></a><br /><a href=\"#ideas-sw-yx\" title=\"Ideas, Planning, & Feedback\">🤔</a> <a href=\"https://github.com/typescript-cheatsheets/react/pulls?q=is%3Apr+reviewed-by%3Asw-yx\" title=\"Reviewed Pull Requests\">👀</a> <a href=\"#maintenance-sw-yx\" title=\"Maintenance\">🚧</a> <a href=\"#content-sw-yx\" title=\"Content\">🖋</a> <a href=\"#question-sw-yx\" title=\"Answering Questions\">💬</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/eps1lon\"><img src=\"https://avatars3.githubusercontent.com/u/12292047?v=4?s=100\" width=\"100px;\" alt=\"Sebastian Silbermann\"/><br /><sub><b>Sebastian Silbermann</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/pulls?q=is%3Apr+reviewed-by%3Aeps1lon\" title=\"Reviewed Pull Requests\">👀</a> <a href=\"#maintenance-eps1lon\" title=\"Maintenance\">🚧</a> <a href=\"#content-eps1lon\" title=\"Content\">🖋</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://www.linkedin.com/in/islam-attrash-46703a94/\"><img src=\"https://avatars0.githubusercontent.com/u/7091543?v=4?s=100\" width=\"100px;\" alt=\"Islam Attrash\"/><br /><sub><b>Islam Attrash</b></sub></a><br /><a href=\"#maintenance-Attrash-Islam\" title=\"Maintenance\">🚧</a> <a href=\"#content-Attrash-Islam\" title=\"Content\">🖋</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://stephenkoo.github.io/\"><img src=\"https://avatars2.githubusercontent.com/u/18624246?v=4?s=100\" width=\"100px;\" alt=\"Stephen Koo\"/><br /><sub><b>Stephen Koo</b></sub></a><br /><a href=\"#question-stephenkoo\" title=\"Answering Questions\">💬</a> <a href=\"#example-stephenkoo\" title=\"Examples\">💡</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/andreasgruenh\"><img src=\"https://avatars2.githubusercontent.com/u/12122390?v=4?s=100\" width=\"100px;\" alt=\"Andreas\"/><br /><sub><b>Andreas</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=andreasgruenh\" title=\"Code\">💻</a> <a href=\"https://github.com/typescript-cheatsheets/react/commits?author=andreasgruenh\" title=\"Documentation\">📖</a> <a href=\"#infra-andreasgruenh\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/arvindcheenu\"><img src=\"https://avatars2.githubusercontent.com/u/13925213?v=4?s=100\" width=\"100px;\" alt=\"Arvind Srinivasan\"/><br /><sub><b>Arvind Srinivasan</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=arvindcheenu\" title=\"Code\">💻</a> <a href=\"#content-arvindcheenu\" title=\"Content\">🖋</a> <a href=\"https://github.com/typescript-cheatsheets/react/commits?author=arvindcheenu\" title=\"Documentation\">📖</a> <a href=\"#maintenance-arvindcheenu\" title=\"Maintenance\">🚧</a></td>\n    </tr>\n    <tr>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"http://www.williamrjribeiro.com\"><img src=\"https://avatars2.githubusercontent.com/u/1503499?v=4?s=100\" width=\"100px;\" alt=\"William R. J. Ribeiro\"/><br /><sub><b>William R. J. Ribeiro</b></sub></a><br /><a href=\"#ideas-williamrjribeiro\" title=\"Ideas, Planning, & Feedback\">🤔</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://alexandrudanpop.dev/\"><img src=\"https://avatars0.githubusercontent.com/u/15979292?v=4?s=100\" width=\"100px;\" alt=\"Alexandru-Dan Pop\"/><br /><sub><b>Alexandru-Dan Pop</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=alexandrudanpop\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/mastorm\"><img src=\"https://avatars1.githubusercontent.com/u/10759336?v=4?s=100\" width=\"100px;\" alt=\"Mathias Storm\"/><br /><sub><b>Mathias Storm</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=mastorm\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://twitter.com/dance2die\"><img src=\"https://avatars1.githubusercontent.com/u/8465237?v=4?s=100\" width=\"100px;\" alt=\"Sung M. Kim\"/><br /><sub><b>Sung M. Kim</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=dance2die\" title=\"Documentation\">📖</a> <a href=\"#ideas-dance2die\" title=\"Ideas, Planning, & Feedback\">🤔</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://ryota-murakami.github.io/\"><img src=\"https://avatars2.githubusercontent.com/u/5501268?v=4?s=100\" width=\"100px;\" alt=\"Ryota Murakami\"/><br /><sub><b>Ryota Murakami</b></sub></a><br /><a href=\"#example-ryota-murakami\" title=\"Examples\">💡</a> <a href=\"https://github.com/typescript-cheatsheets/react/commits?author=ryota-murakami\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/arpi17\"><img src=\"https://avatars1.githubusercontent.com/u/13800404?v=4?s=100\" width=\"100px;\" alt=\"Árpád Illyés\"/><br /><sub><b>Árpád Illyés</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=arpi17\" title=\"Code\">💻</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://twitter.com/xamgore\"><img src=\"https://avatars3.githubusercontent.com/u/4586392?v=4?s=100\" width=\"100px;\" alt=\"Igor Strebezhev\"/><br /><sub><b>Igor Strebezhev</b></sub></a><br /><a href=\"#ideas-xamgore\" title=\"Ideas, Planning, & Feedback\">🤔</a> <a href=\"https://github.com/typescript-cheatsheets/react/commits?author=xamgore\" title=\"Documentation\">📖</a></td>\n    </tr>\n    <tr>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://geoplanets.io\"><img src=\"https://avatars2.githubusercontent.com/u/2467377?v=4?s=100\" width=\"100px;\" alt=\"David Johnston\"/><br /><sub><b>David Johnston</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=dwjohnston\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/kripod\"><img src=\"https://avatars3.githubusercontent.com/u/14854048?v=4?s=100\" width=\"100px;\" alt=\"Kristóf Poduszló\"/><br /><sub><b>Kristóf Poduszló</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=kripod\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"http://www.novusstudio.com/\"><img src=\"https://avatars3.githubusercontent.com/u/10838852?v=4?s=100\" width=\"100px;\" alt=\"james glasgow\"/><br /><sub><b>james glasgow</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=glaschu1\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://www.linkedin.com/in/iigrekov/\"><img src=\"https://avatars0.githubusercontent.com/u/13730032?v=4?s=100\" width=\"100px;\" alt=\"Ivan\"/><br /><sub><b>Ivan</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=Winner95\" title=\"Code\">💻</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"http://sebastianandil.com\"><img src=\"https://avatars1.githubusercontent.com/u/6603389?v=4?s=100\" width=\"100px;\" alt=\"Sebastian Andil\"/><br /><sub><b>Sebastian Andil</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=selrond\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/adnanhusain15\"><img src=\"https://avatars2.githubusercontent.com/u/36721076?v=4?s=100\" width=\"100px;\" alt=\"Adnan Husain\"/><br /><sub><b>Adnan Husain</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=adnanhusain15\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/artola\"><img src=\"https://avatars0.githubusercontent.com/u/11500763?v=4?s=100\" width=\"100px;\" alt=\"martin\"/><br /><sub><b>martin</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=artola\" title=\"Documentation\">📖</a></td>\n    </tr>\n    <tr>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://tammergard.se\"><img src=\"https://avatars.githubusercontent.com/u/44197016?v=4?s=100\" width=\"100px;\" alt=\"Filip Tammergård\"/><br /><sub><b>Filip Tammergård</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=filiptammergard\" title=\"Documentation\">📖</a> <a href=\"https://github.com/typescript-cheatsheets/react/commits?author=filiptammergard\" title=\"Code\">💻</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://englishbyte.com\"><img src=\"https://avatars.githubusercontent.com/u/3806031?v=4?s=100\" width=\"100px;\" alt=\"Joe Previte\"/><br /><sub><b>Joe Previte</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=jsjoeio\" title=\"Documentation\">📖</a></td>\n      <td align=\"center\" valign=\"top\" width=\"14.28%\"><a href=\"https://github.com/sasirura\"><img src=\"https://avatars.githubusercontent.com/u/42542164?v=4?s=100\" width=\"100px;\" alt=\"Sasiru Ravihansa\"/><br /><sub><b>Sasiru Ravihansa</b></sub></a><br /><a href=\"https://github.com/typescript-cheatsheets/react/commits?author=sasirura\" title=\"Documentation\">📖</a></td>\n    </tr>\n  </tbody>\n</table>\n\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 shawn wang\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# React TypeScript Cheatsheet\n\nCheatsheet for using React with TypeScript.\n\n---\n\n<a href=\"https://github.com/typescript-cheatsheets/react/issues/81\">\n  <img\n    height=\"90\"\n    width=\"90\"\n    alt=\"react + ts logo\"\n    src=\"https://user-images.githubusercontent.com/84442212/194379444-02e5ec69-5e6c-4100-bd7a-c31d628af29c.png\"\n    align=\"left\"\n  />\n</a>\n\n[**Web docs**](https://react-typescript-cheatsheet.netlify.app/docs/basic/setup) |\n[Contribute!](https://github.com/typescript-cheatsheets/react/blob/main/CONTRIBUTING.md) |\n[Ask!](https://github.com/typescript-cheatsheets/react/issues/new/choose)\n\n:wave: This repo is maintained by [@eps1lon](https://twitter.com/sebsilbermann) and [@filiptammergard](https://twitter.com/tammergard). We're so happy you want to try out React with TypeScript! If you see anything wrong or missing, please [file an issue](https://github.com/typescript-cheatsheets/react/issues/new/choose)! :+1:\n\n---\n\n[![All Contributors](https://img.shields.io/github/contributors/typescript-cheatsheets/react-typescript-cheatsheet?color=orange&style=flat-square)](/CONTRIBUTORS.md) | [![Discord](https://img.shields.io/discord/508357248330760243.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/wTGS5z9)\n\n- [The Basic Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/basic/setup) is focused on helping React devs just start using TS in React **apps**\n  - Focus on opinionated best practices, copy+pastable examples.\n  - Explains some basic TS types usage and setup along the way.\n  - Answers the most Frequently Asked Questions.\n  - Does not cover generic type logic in detail. Instead we prefer to teach simple troubleshooting techniques for newbies.\n  - The goal is to get effective with TS without learning _too much_ TS.\n- [The Advanced Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/advanced) helps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+React **libraries**.\n  - It also has miscellaneous tips and tricks for pro users.\n  - Advice for contributing to DefinitelyTyped.\n  - The goal is to take _full advantage_ of TypeScript.\n- [The Migrating Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/migration) helps collate advice for incrementally migrating large codebases from JS or Flow, **from people who have done it**.\n  - We do not try to convince people to switch, only to help people who have already decided.\n  - ⚠️This is a new cheatsheet, all assistance is welcome.\n- [The HOC Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/hoc) specifically teaches people to write HOCs with examples.\n  - Familiarity with [Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html) is necessary.\n  - ⚠️This is the newest cheatsheet, all assistance is welcome.\n\n---\n\n## Basic Cheatsheet\n\n### Basic Cheatsheet Table of Contents\n\n<details>\n\n<summary><b>Expand Table of Contents</b></summary>\n\n- [React TypeScript Cheatsheet](#react-typescript-cheatsheet)\n  - [Basic Cheatsheet](#basic-cheatsheet)\n    - [Basic Cheatsheet Table of Contents](#basic-cheatsheet-table-of-contents)\n    - [Section 1: Setup](#section-1-setup)\n      - [Prerequisites](#prerequisites)\n      - [React and TypeScript starter kits](#react-and-typescript-starter-kits)\n      - [Try React and TypeScript online](#try-react-and-typescript-online)\n    - [Section 2: Getting Started](#section-2-getting-started)\n      - [Function Components](#function-components)\n      - [Hooks](#hooks)\n      - [useState](#usestate)\n      - [useCallback](#usecallback)\n      - [useReducer](#usereducer)\n      - [useEffect / useLayoutEffect](#useeffect--uselayouteffect)\n      - [useRef](#useref)\n        - [Option 1: DOM element ref](#option-1-dom-element-ref)\n        - [Option 2: Mutable value ref](#option-2-mutable-value-ref)\n        - [See also](#see-also)\n      - [useImperativeHandle](#useimperativehandle)\n        - [See also:](#see-also-1)\n      - [Custom Hooks](#custom-hooks)\n      - [More Hooks + TypeScript reading:](#more-hooks--typescript-reading)\n      - [Example React Hooks + TypeScript Libraries:](#example-react-hooks--typescript-libraries)\n      - [Class Components](#class-components)\n      - [Typing getDerivedStateFromProps](#typing-getderivedstatefromprops)\n      - [You May Not Need `defaultProps`](#you-may-not-need-defaultprops)\n      - [Typing `defaultProps`](#typing-defaultprops)\n      - [Consuming Props of a Component with defaultProps](#consuming-props-of-a-component-with-defaultprops)\n        - [Problem Statement](#problem-statement)\n        - [Solution](#solution)\n      - [Misc Discussions and Knowledge](#misc-discussions-and-knowledge)\n      - [Typing Component Props](#typing-component-props)\n      - [Basic Prop Types Examples](#basic-prop-types-examples)\n        - [`object` as the non-primitive type](#object-as-the-non-primitive-type)\n        - [Empty interface, `{}` and `Object`](#empty-interface--and-object)\n      - [Useful React Prop Type Examples](#useful-react-prop-type-examples)\n      - [Types or Interfaces?](#types-or-interfaces)\n        - [TL;DR](#tldr)\n        - [More Advice](#more-advice)\n        - [Useful table for Types vs Interfaces](#useful-table-for-types-vs-interfaces)\n  - [getDerivedStateFromProps](#getderivedstatefromprops)\n    - [Forms and Events](#forms-and-events)\n      - [List of event types](#list-of-event-types)\n    - [Context](#context)\n    - [Basic example](#basic-example)\n    - [Without default context value](#without-default-context-value)\n      - [Type assertion as an alternative](#type-assertion-as-an-alternative)\n    - [forwardRef/createRef](#forwardrefcreateref)\n    - [Generic forwardRefs](#generic-forwardrefs)\n      - [Option 1 - Wrapper component](#option-1---wrapper-component)\n      - [Option 2 - Redeclare forwardRef](#option-2---redeclare-forwardref)\n      - [Option 3 - Call signature](#option-3---call-signature)\n    - [More Info](#more-info)\n    - [Portals](#portals)\n    - [Error Boundaries](#error-boundaries)\n      - [Option 1: Using react-error-boundary](#option-1-using-react-error-boundary)\n      - [Option 2: Writing your custom error boundary component](#option-2-writing-your-custom-error-boundary-component)\n    - [Concurrent React/React Suspense](#concurrent-reactreact-suspense)\n    - [Troubleshooting Handbook: Types](#troubleshooting-handbook-types)\n      - [Union Types and Type Guarding](#union-types-and-type-guarding)\n      - [Optional Types](#optional-types)\n      - [Enum Types](#enum-types)\n      - [Type Assertion](#type-assertion)\n      - [Simulating Nominal Types](#simulating-nominal-types)\n      - [Intersection Types](#intersection-types)\n      - [Union Types](#union-types)\n      - [Overloading Function Types](#overloading-function-types)\n      - [Using Inferred Types](#using-inferred-types)\n      - [Using Partial Types](#using-partial-types)\n      - [The Types I need weren't exported!](#the-types-i-need-werent-exported)\n      - [The Types I need don't exist!](#the-types-i-need-dont-exist)\n        - [Slapping `any` on everything](#slapping-any-on-everything)\n        - [Autogenerate types](#autogenerate-types)\n        - [Typing Exported Hooks](#typing-exported-hooks)\n        - [Typing Exported Components](#typing-exported-components)\n      - [Frequent Known Problems with TypeScript](#frequent-known-problems-with-typescript)\n        - [TypeScript doesn't narrow after an object element null check](#typescript-doesnt-narrow-after-an-object-element-null-check)\n        - [TypeScript doesn't let you restrict the type of children](#typescript-doesnt-let-you-restrict-the-type-of-children)\n    - [Troubleshooting Handbook: Operators](#troubleshooting-handbook-operators)\n    - [Troubleshooting Handbook: Utilities](#troubleshooting-handbook-utilities)\n    - [Troubleshooting Handbook: tsconfig.json](#troubleshooting-handbook-tsconfigjson)\n    - [Troubleshooting Handbook: Fixing bugs in official typings](#troubleshooting-handbook-fixing-bugs-in-official-typings)\n    - [Troubleshooting Handbook: Globals, Images and other non-TS files](#troubleshooting-handbook-globals-images-and-other-non-ts-files)\n    - [Editor Tooling and Integration](#editor-tooling-and-integration)\n    - [Linting](#linting)\n    - [Other React + TypeScript resources](#other-react--typescript-resources)\n    - [Recommended React + TypeScript talks](#recommended-react--typescript-talks)\n    - [Time to Really Learn TypeScript](#time-to-really-learn-typescript)\n    - [Example App](#example-app)\n  - [My question isn't answered here!](#my-question-isnt-answered-here)\n  - [Contributors](#contributors)\n\n</details>\n\n<!--START-SECTION:setup-->\n\n### Section 1: Setup\n\n#### Prerequisites\n\nYou can use this cheatsheet for reference at any skill level, but basic understanding of React and TypeScript is assumed. Here is a list of prerequisites:\n\n- Basic understanding of [React](https://react.dev/).\n- Familiarity with [TypeScript Basics](https://www.typescriptlang.org/docs/handbook/2/basic-types.html) and [Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html).\n\nIn the cheatsheet we assume you are using the latest versions of React and TypeScript.\n\n#### React and TypeScript starter kits\n\nReact has documentation for [how to start a new React project](https://react.dev/learn/start-a-new-react-project) with some of the most popular frameworks. Here's how to start them with TypeScript:\n\n- [Next.js](https://nextjs.org/docs/basic-features/typescript): `npx create-next-app@latest --ts`\n- [Remix](https://remix.run/docs/tutorials/blog): `npx create-remix@latest`\n- [Gatsby](https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/): `npm init gatsby --ts`\n- [Expo](https://docs.expo.dev/guides/typescript/): `npx create-expo-app -t with-typescript`\n\n#### Try React and TypeScript online\n\nThere are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.\n\n- [TypeScript playground](https://www.typescriptlang.org/play?target=8&jsx=4#code/JYWwDg9gTgLgBAbzgVwM4FMDKMCGN0A0KGAogGZnoDG8AvnGVBCHAORTo42sDcAsAChB6AB6RYcKhAB2qeAGEIyafihwAvHAAUASg0A+RILiSZcuAG0pymEQwxFNgLobiWXPi0AGHfyECTNHRyShotXQMjAJM4ABMIKmQQdBUAOhhgGAAbdFcAAwBNJUks4CoAa3RYuAASBGsVegzk1Dy-E1pfQWM4DhhkKGltHpMAHn0RmNGwfSLkErLK6vqlRrhm9FRRgHoZybGAI2QYGBk4GXlSivUECPVDe0cVLQb4AGo4AEYdWgnomJil0WcGS+zgOyOJxkfwBOxhcC6AlogiAA)\n- [StackBlitz](https://stackblitz.com/fork/react-ts)\n- [CodeSandbox](https://ts.react.new/)\n\n<!--END-SECTION:setup-->\n\n### Section 2: Getting Started\n\n<!--START-SECTION:function-components-->\n\n#### Function Components\n\nThese can be written as normal functions that take a `props` argument and return a JSX element.\n\n```tsx\n// Declaring type of props - see \"Typing Component Props\" for more examples\ntype AppProps = {\n  message: string;\n}; /* use `interface` if exporting so that consumers can extend */\n\n// Easiest way to declare a Function Component; return type is inferred.\nconst App = ({ message }: AppProps) => <div>{message}</div>;\n\n// You can choose to annotate the return type so an error is raised if you accidentally return some other type\nconst App = ({ message }: AppProps): React.JSX.Element => <div>{message}</div>;\n\n// You can also inline the type declaration; eliminates naming the prop types, but looks repetitive\nconst App = ({ message }: { message: string }) => <div>{message}</div>;\n\n// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.\n// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.\nconst App: React.FunctionComponent<{ message: string }> = ({ message }) => (\n  <div>{message}</div>\n);\n// or\nconst App: React.FC<AppProps> = ({ message }) => <div>{message}</div>;\n```\n\n> Tip: You might use [Paul Shen's VS Code Extension](https://marketplace.visualstudio.com/items?itemName=paulshen.paul-typescript-toolkit) to automate the type destructure declaration (incl a [keyboard shortcut](https://twitter.com/_paulshen/status/1392915279466745857?s=20)).\n\n<details>\n\n<summary><b>Why is <code>React.FC</code> not needed? What about <code>React.FunctionComponent</code>/<code>React.VoidFunctionComponent</code>?</b></summary>\n\nYou may see this in many React+TypeScript codebases:\n\n```tsx\nconst App: React.FunctionComponent<{ message: string }> = ({ message }) => (\n  <div>{message}</div>\n);\n```\n\nHowever, the general consensus today is that `React.FunctionComponent` (or the shorthand `React.FC`) is not needed. If you're still using React 17 or TypeScript lower than 5.1, it is even [discouraged](https://github.com/facebook/create-react-app/pull/8177). This is a nuanced opinion of course, but if you agree and want to remove `React.FC` from your codebase, you can use [this jscodeshift codemod](https://github.com/gndelia/codemod-replace-react-fc-typescript).\n\nSome differences from the \"normal function\" version:\n\n- `React.FunctionComponent` is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).\n\n- It provides typechecking and autocomplete for static properties like `displayName`, `propTypes`, and `defaultProps`.\n\n  - Note that there are some known issues using `defaultProps` with `React.FunctionComponent`. See [this issue for details](https://github.com/typescript-cheatsheets/react/issues/87). We maintain a separate `defaultProps` section you can also look up.\n\n- Before the [React 18 type updates](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210), `React.FunctionComponent` provided an implicit definition of `children` (see below), which was heavily debated and is one of the reasons [`React.FC` was removed from the Create React App TypeScript template](https://github.com/facebook/create-react-app/pull/8177).\n\n```tsx\n// before React 18 types\nconst Title: React.FunctionComponent<{ title: string }> = ({\n  children,\n  title,\n}) => <div title={title}>{children}</div>;\n```\n\n<details>\n<summary>(Deprecated)<b>Using <code>React.VoidFunctionComponent</code> or <code>React.VFC</code> instead</b></summary>\n\nIn [@types/react 16.9.48](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643), the `React.VoidFunctionComponent` or `React.VFC` type was added for typing `children` explicitly.\nHowever, please be aware that `React.VFC` and `React.VoidFunctionComponent` were deprecated in React 18 (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/59882), so this interim solution is no longer necessary or recommended in React 18+.\n\nPlease use regular function components or `React.FC` instead.\n\n```ts\ntype Props = { foo: string };\n\n// OK now, in future, error\nconst FunctionComponent: React.FunctionComponent<Props> = ({\n  foo,\n  children,\n}: Props) => {\n  return (\n    <div>\n      {foo} {children}\n    </div>\n  ); // OK\n};\n\n// Error now, in future, deprecated\nconst VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({\n  foo,\n  children,\n}) => {\n  return (\n    <div>\n      {foo}\n      {children}\n    </div>\n  );\n};\n```\n\n</details>\n\n- _In the future_, it may automatically mark props as `readonly`, though that's a moot point if the props object is destructured in the parameter list.\n\nIn most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of `React.FunctionComponent`.\n\n</details>\n\n<!--END-SECTION:function-components-->\n\n<!--START-SECTION:hooks-->\n\n#### Hooks\n\nHooks are [supported in `@types/react` from v16.8 up](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031).\n\n#### useState\n\nType inference works very well for simple values:\n\n```tsx\nconst [state, setState] = useState(false);\n// `state` is inferred to be a boolean\n// `setState` only takes booleans\n```\n\nSee also the [Using Inferred Types](https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types/#using-inferred-types) section if you need to use a complex type that you've relied on inference for.\n\nHowever, many hooks are initialized with null-ish default values, and you may wonder how to provide types. Explicitly declare the type, and use a union type:\n\n```tsx\nconst [user, setUser] = useState<User | null>(null);\n\n// later...\nsetUser(newUser);\n```\n\nYou can also use type assertions if a state is initialized soon after setup and always has a value after:\n\n```tsx\nconst [user, setUser] = useState<User>({} as User);\n\n// later...\nsetUser(newUser);\n```\n\nThis temporarily \"lies\" to the TypeScript compiler that `{}` is of type `User`. You should follow up by setting the `user` state — if you don't, the rest of your code may rely on the fact that `user` is of type `User` and that may lead to runtime errors.\n\n#### useCallback\n\nYou can type the `useCallback` just like any other function.\n\n```ts\nconst memoizedCallback = useCallback(\n  (param1: string, param2: number) => {\n    console.log(param1, param2)\n    return { ok: true }\n  },\n  [...],\n);\n/**\n * VSCode will show the following type:\n * const memoizedCallback:\n *  (param1: string, param2: number) => { ok: boolean }\n */\n```\n\nNote that for React < 18, the function signature of `useCallback` typed arguments as `any[]` by default:\n\n```ts\nfunction useCallback<T extends (...args: any[]) => any>(\n  callback: T,\n  deps: DependencyList\n): T;\n```\n\nIn React >= 18, the function signature of `useCallback` changed to the following:\n\n```ts\nfunction useCallback<T extends Function>(callback: T, deps: DependencyList): T;\n```\n\nTherefore, the following code will yield \"`Parameter 'e' implicitly has an 'any' type.`\" error in React >= 18, but not <17.\n\n```ts\n// @ts-expect-error Parameter 'e' implicitly has 'any' type.\nuseCallback((e) => {}, []);\n// Explicit 'any' type.\nuseCallback((e: any) => {}, []);\n```\n\n#### useReducer\n\nYou can use [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions) for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.\n\n```tsx\nimport { useReducer } from \"react\";\n\nconst initialState = { count: 0 };\n\ntype ACTIONTYPE =\n  | { type: \"increment\"; payload: number }\n  | { type: \"decrement\"; payload: string };\n\nfunction reducer(state: typeof initialState, action: ACTIONTYPE) {\n  switch (action.type) {\n    case \"increment\":\n      return { count: state.count + action.payload };\n    case \"decrement\":\n      return { count: state.count - Number(action.payload) };\n    default:\n      throw new Error();\n  }\n}\n\nfunction Counter() {\n  const [state, dispatch] = useReducer(reducer, initialState);\n  return (\n    <>\n      Count: {state.count}\n      <button onClick={() => dispatch({ type: \"decrement\", payload: \"5\" })}>\n        -\n      </button>\n      <button onClick={() => dispatch({ type: \"increment\", payload: 5 })}>\n        +\n      </button>\n    </>\n  );\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6WfTDRSvKnMgpEIgBhxTIJwEQANZSWRjI5SdPIF1u8RXMayZ7lSphEnRWLxbFNagAVmomhF6fZqYA9OXKxxM2KQWWK1WoTW643m63pB2u+7e-3SkEQsPamOGik1FO55p08jl6vdxuKcvv8h4yAmhAA)\n\n<details>\n\n<summary><b>Usage with <code>Reducer</code> from <code>redux</code></b></summary>\n\nIn case you use the [redux](https://github.com/reduxjs/redux) library to write reducer function, It provides a convenient helper of the format `Reducer<State, Action>` which takes care of the return type for you.\n\nSo the above reducer example becomes:\n\n```tsx\nimport { Reducer } from 'redux';\n\nexport function reducer: Reducer<AppState, Action>() {}\n```\n\n</details>\n\n#### useEffect / useLayoutEffect\n\nBoth of `useEffect` and `useLayoutEffect` are used for performing <b>side effects</b> and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When using `useEffect`, take care not to return anything other than a function or `undefined`, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:\n\n```ts\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(\n    () =>\n      setTimeout(() => {\n        /* do stuff */\n      }, timerMs),\n    [timerMs]\n  );\n  // bad example! setTimeout implicitly returns a number\n  // because the arrow function body isn't wrapped in curly braces\n  return null;\n}\n```\n\n<details>\n<summary><b>Solution to the above example</b></summary>\n\n```tsx\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(() => {\n    setTimeout(() => {\n      /* do stuff */\n    }, timerMs);\n  }, [timerMs]);\n  // better; use the void keyword to make sure you return undefined\n  return null;\n}\n```\n\n</details>\n\n#### useRef\n\nIn TypeScript, `useRef` returns a reference that is either [read-only](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1025-L1039) or [mutable](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1012-L1023), depends on whether your type argument fully covers the initial value or not. Choose one that suits your use case.\n\n##### Option 1: DOM element ref\n\n**[To access a DOM element](https://reactjs.org/docs/refs-and-the-dom.html):** provide only the element type as argument, and use `null` as initial value. In this case, the returned reference will have a read-only `.current` that is managed by React. TypeScript expects you to give this ref to an element's `ref` prop:\n\n```tsx\nfunction Foo() {\n  // - If possible, prefer as specific as possible. For example, HTMLDivElement\n  //   is better than HTMLElement and way better than Element.\n  // - Technical-wise, this returns RefObject<HTMLDivElement>\n  const divRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    // Note that ref.current may be null. This is expected, because you may\n    // conditionally render the ref-ed element, or you may forget to assign it\n    if (!divRef.current) throw Error(\"divRef is not assigned\");\n\n    // Now divRef.current is sure to be HTMLDivElement\n    doSomethingWith(divRef.current);\n  });\n\n  // Give the ref to an element so React can manage it for you\n  return <div ref={divRef}>etc</div>;\n}\n```\n\nIf you are sure that `divRef.current` will never be null, it is also possible to use the non-null assertion operator `!`:\n\n```tsx\nconst divRef = useRef<HTMLDivElement>(null!);\n// Later... No need to check if it is null\ndoSomethingWith(divRef.current);\n```\n\nNote that you are opting out of type safety here - you will have a runtime error if you forget to assign the ref to an element in the render, or if the ref-ed element is conditionally rendered.\n\n<details>\n<summary><b>Tip: Choosing which <code>HTMLElement</code> to use</b></summary>\n  \nRefs demand specificity - it is not enough to just specify any old `HTMLElement`. If you don't know the name of the element type you need, you can check [lib.dom.ts](https://github.com/microsoft/TypeScript/blob/v3.9.5/lib/lib.dom.d.ts#L19224-L19343) or make an intentional type error and let the language service tell you:\n\n![image](https://user-images.githubusercontent.com/6764957/116914284-1c436380-ac7d-11eb-9150-f52c571c5f07.png)\n\n</details>\n\n##### Option 2: Mutable value ref\n\n**[To have a mutable value](https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables):** provide the type you want, and make sure the initial value fully belongs to that type:\n\n```tsx\nfunction Foo() {\n  // Technical-wise, this returns MutableRefObject<number | null>\n  const intervalRef = useRef<number | null>(null);\n\n  // You manage the ref yourself (that's why it's called MutableRefObject!)\n  useEffect(() => {\n    intervalRef.current = setInterval(...);\n    return () => clearInterval(intervalRef.current);\n  }, []);\n\n  // The ref is not passed to any element's \"ref\" prop\n  return <button onClick={/* clearInterval the ref */}>Cancel timer</button>;\n}\n```\n\n##### See also\n\n- [Related issue by @rajivpunjabi](https://github.com/typescript-cheatsheets/react/issues/388) - [Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwCwAUI7hAHarwCCYYcAvHAAUASn4A+OAG9GjOHAD0CBLLnKGcxHABiwKBzgQwMYGxS4WUACbBWAczgwIcSxFwBXEFlYxkxtgDoVTQBJVmBjZAAbOAA3KLcsOAB3YEjogCNE1jc0-zgAGQBPG3tHOAAVQrAsAGVcKGAjOHTCuDdUErhWNgBabLSUVFQsWBNWA2qoX2hA9VU4AGFKXyx0AFk3H3TIxOwCOAB5dIArLHwgpHcoSm84MGJJmFbgdG74ZcsDVkjC2Y01f7yFQsdjvLAEACM-EwVBg-naWD2AB4ABLlNb5GpgZCsACiO083jEgn6kQAhMJ6HMQfpKJCFpE2IkBNg8HCEci0RisTj8VhCTBiaSKVSVIoAaoLnBQuFgFFYvFEikBpkujkMps4FgAB7VfCdLmY7F4gleOFwAByEHg7U63VYfXVg2Go1MhhG0ygf3mAHVUtF6jgYLtwUdTvguta4Bstjs9mGznCpVcbvB7u7YM90B8vj9vYgLkDqWxaeCAEzQ1n4eHDTnoo2801EknqykyObii5SmpnNifA5GMZmCzWOwOJwudwC3xjKUyiLROKRBLJf3NLJO9KanV64xj0koVifQ08k38s1Sv0DJZBxIx5DbRGhk6J5Nua5mu4PEZPOAvSNgsgnxsHmXZzIgRZyDSYIEAAzJWsI1k+BCovWp58gKcAAD5qmkQqtqKHbyCexoYRecw7IQugcAs76ptCdIQv4KZmoRcjyMRaGkU28A4aSKiUXAwwgpYtEfrcAh0mWzF0ax7bsZx3Lceetx8eqAlYPAMAABa6KJskSXAdKwTJ4kwGxCjyKy-bfK05SrDA8mWVagHAbZeScOY0CjqUE6uOgqDaRAOSfKqOYgb8KiMaZ9GSeCEIMkyMVyUwRHWYc7nSvAgUQEk6AjMQXpReWyWGdFLHeBZHEuTCQEZT8xVwaV8BxZCzUWZQMDvuMghBHASJVnCWhTLYApiH1chIqgxpGeCfCSIxAC+Yj3o+8YvvgSLyNNOLjeBGhTTNdLzVJy3reGMBbTtrB7RoB3XbNBAneCsHLatcbPhdV3GrdB1WYhw3IKNZq-W2DCLYRO7QPAljgsgORcDwVJAA)\n- [Example from Stefan Baumgartner](https://fettblog.eu/typescript-react/hooks/#useref) - [Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wFgAoCzAVwDsNgJa4AVJADxgElaxqYA6sBgALAGIQ01AM4AhfjCYAKAJRwA3hThwA9DrjBaw4CgA2waUjgB3YSLi1qp0wBo4AI35wYSZ6wCeYEgAymhQwGDw1lYoRHCmEBAA1oYA5nCY0HAozAASLACyADI8fDAAoqZIIEi0MFpwaEzS8IZllXAAvIjEMAB0MkjImAA8+cWl-JXVtTAAfEqOzioA3A1NtC1wTPIwirQAwuZoSV1wql1zGg3aenAt4RgOTqaNIkgn0g5ISAAmcDJvBA3h9TsBMAZeFNXjl-lIoEQ6nAOBZ+jddPpPPAmGgrPDEfAUS1pG5hAYvhAITBAlZxiUoRUqjU6m5RIDhOi7iIUF9RFYaqIIP9MlJpABCOCAUHJ0eDzm1oXAAGSKyHtUx9fGzNSacjaPWq6Ea6gI2Z9EUyVRrXV6gC+DRtVu0RBgxuYSnRIzm6O06h0ACpIdlfr9jExSQyOkxTP5GjkPFZBv9bKIDYSmbNpH04ABNFD+CV+nR2636kby+BETCddTlyo27w0zr4HycfC6L0lvUjLH7baHY5Jas7BRMI7AE42uYSUXed6pkY6HtMDulnQruCrCg2oA)\n\n#### useImperativeHandle\n\nBased on this [Stackoverflow answer](https://stackoverflow.com/a/69292925/5415299):\n\n```tsx\n// Countdown.tsx\n\n// Define the handle types which will be passed to the forwardRef\nexport type CountdownHandle = {\n  start: () => void;\n};\n\ntype CountdownProps = {};\n\nconst Countdown = forwardRef<CountdownHandle, CountdownProps>((props, ref) => {\n  useImperativeHandle(ref, () => ({\n    // start() has type inference here\n    start() {\n      alert(\"Start\");\n    },\n  }));\n\n  return <div>Countdown</div>;\n});\n```\n\n```tsx\n// The component uses the Countdown component\n\nimport Countdown, { CountdownHandle } from \"./Countdown.tsx\";\n\nfunction App() {\n  const countdownEl = useRef<CountdownHandle>(null);\n\n  useEffect(() => {\n    if (countdownEl.current) {\n      // start() has type inference here as well\n      countdownEl.current.start();\n    }\n  }, []);\n\n  return <Countdown ref={countdownEl} />;\n}\n```\n\n##### See also:\n\n- [Using ForwardRefRenderFunction](https://stackoverflow.com/a/62258685/5415299)\n\n#### Custom Hooks\n\nIf you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScript will infer a union type (when you actually want different types in each position of the array). Instead, use [TS 3.4 const assertions](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions):\n\n```tsx\nimport { useState } from \"react\";\n\nexport function useLoading() {\n  const [isLoading, setState] = useState(false);\n  const load = (aPromise: Promise<any>) => {\n    setState(true);\n    return aPromise.finally(() => setState(false));\n  };\n  return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?target=5&jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCpAD0ljkwFcA7DYCZuRgZyQBkIKACbBmAcwAUASjgBvCnDhoO3eAG1g3AcNFiANHF4wAyjBQwkAXTgBeRMRgA6HklPmkEzCgA2vKQG4FJRV4b0EhWzgJFAAFHBBNJAAuODjcRIAeFGYATwA+GRs8uSDFIzcLCRgoRiQA0rgiGEYoTlj4xMdMUR9vHIlpW2Lys0qvXzr68kUAX0DpxqRm1rgNLXDdAzDhaxRuYOZVfzgAehO4UUwkKH21ACMICG9UZgMYHLAkCEw4baFrUSqVARb5RB5PF5wAA+cHen1BfykaksFBmQA)\n\nThis way, when you destructure you actually get the right types based on destructure position.\n\n<details>\n<summary><b>Alternative: Asserting a tuple return type</b></summary>\n\nIf you are [having trouble with const assertions](https://github.com/babel/babel/issues/9800), you can also assert or define the function return types:\n\n```tsx\nimport { useState } from \"react\";\n\nexport function useLoading() {\n  const [isLoading, setState] = useState(false);\n  const load = (aPromise: Promise<any>) => {\n    setState(true);\n    return aPromise.finally(() => setState(false));\n  };\n  return [isLoading, load] as [\n    boolean,\n    (aPromise: Promise<any>) => Promise<any>\n  ];\n}\n```\n\nA helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:\n\n```tsx\nfunction tuplify<T extends any[]>(...elements: T) {\n  return elements;\n}\n\nfunction useArray() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() => {}).current;\n  return [numberValue, functionValue]; // type is (number | (() => void))[]\n}\n\nfunction useTuple() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() => {}).current;\n  return tuplify(numberValue, functionValue); // type is [number, () => void]\n}\n```\n\n</details>\n\nNote that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however.\n\n#### More Hooks + TypeScript reading:\n\n- https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d\n- https://fettblog.eu/typescript-react/hooks/#useref\n\nIf you are writing a React Hooks library, don't forget that you should also expose your types for users to use.\n\n#### Example React Hooks + TypeScript Libraries:\n\n- https://github.com/mweststrate/use-st8\n- https://github.com/palmerhq/the-platform\n- https://github.com/sw-yx/hooks\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n<!--END-SECTION:hooks-->\n\n<!--START-SECTION:class-components-->\n\n#### Class Components\n\nWithin TypeScript, `React.Component` is a generic type (aka `React.Component<PropType, StateType>`), so you want to provide it with (optional) prop and state type parameters:\n\n```tsx\ntype MyProps = {\n  // using `interface` is also ok\n  message: string;\n};\ntype MyState = {\n  count: number; // like this\n};\nclass App extends React.Component<MyProps, MyState> {\n  state: MyState = {\n    // optional second annotation for better type inference\n    count: 0,\n  };\n  render() {\n    return (\n      <div>\n        {this.props.message} {this.state.count}\n      </div>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgFlqAFHMAZzgF44BvCuHAD0QuAFd2wAHYBzOAANpMJFEzok8uME4oANuwhwIAawFwQSduxQykALjjsYUaTIDcFAL4fyNOo2oAZRgUZW4+MzQIMSkYBykxEAAjFTdhUV1gY3oYAAttLx80XRQrOABBMDA4JAAPZSkAE05kdBgAOgBhXEgpJFiAHiZWCA4AGgDg0KQAPgjyQSdphyYpsJ5+BcF0ozAYYAgpPUckKKa4FCkpCBD9w7hMaDgUmGUoOD96aUwVfrQkMyCKIxOJwAAMZm8ZiITRUAAoAJTzbZwIgwMRQKRwOGA7YDRrAABuM1xKN4eW07TAbHY7QsVhsSE8fAptKWynawNinlJcAGQgJxNxCJ8gh55E8QA)\n\nDon't forget that you can export/import/extend these types/interfaces for reuse.\n\n<details>\n<summary><b>Why annotate <code>state</code> twice?</b></summary>\n\nIt isn't strictly necessary to annotate the `state` class property, but it allows better type inference when accessing `this.state` and also initializing the state.\n\nThis is because they work in two different ways, the 2nd generic type parameter will allow `this.setState()` to work correctly, because that method comes from the base class, but initializing `state` inside the component overrides the base implementation so you have to make sure that you tell the compiler that you're not actually doing anything different.\n\n[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57).\n\n</details>\n\n<details>\n  <summary><b>No need for <code>readonly</code></b></summary>\n\nYou often see sample code include `readonly` to mark props and state immutable:\n\n```tsx\ntype MyProps = {\n  readonly message: string;\n};\ntype MyState = {\n  readonly count: number;\n};\n```\n\nThis is not necessary as `React.Component<P,S>` already marks them as immutable. ([See PR and discussion!](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813))\n\n</details>\n\n**Class Methods**: Do it like normal, but just remember any arguments for your functions also need to be typed:\n\n```tsx\nclass App extends React.Component<{ message: string }, { count: number }> {\n  state = { count: 0 };\n  render() {\n    return (\n      <div onClick={() => this.increment(1)}>\n        {this.props.message} {this.state.count}\n      </div>\n    );\n  }\n  increment = (amt: number) => {\n    // like this\n    this.setState((state) => ({\n      count: state.count + amt,\n    }));\n  };\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN5wQSBigDmSAFxw6MKMB5q4AXwA0cRWggBXHjG09rIAEZIoJgHwWKcHTBTccAC8FnBWtvZwAAwmANw+cET8bgAUAJTe5L6+RDDWUDxwKQnZcLJ8wABucBA8YtTAaADWQfLpwV4wABbAdCIGaETKdikAjGnGHiWlFt29ImA4YH3KqhrGsz19ugFIIuF2xtO+sgD0FZVTWdlp8ddH1wNDMsFFKCCRji5uGUFe8tNTqc4A0mkg4HM6NNISI6EgYABlfzcFI7QJ-IoA66lA6RNF7XFwADUcHeMGmxjStwSxjuxiAA)\n\n**Class Properties**: If you need to declare class properties for later use, just declare it like `state`, but without assignment:\n\n```tsx\nclass App extends React.Component<{\n  message: string;\n}> {\n  pointer: number; // like this\n  componentDidMount() {\n    this.pointer = 3;\n  }\n  render() {\n    return (\n      <div>\n        {this.props.message} and {this.pointer}\n      </div>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN4U4cEEgYoA5kgBccOjCjAeGgNwUAvgD44i8sshHuUXTwCuIAEZIoJuAHo-OGpgAGskOBgAC2A6JTg0SQhpHhgAEWA+AFkIVxSACgBKGzjlKJiRBxTvOABeOABmMzs4cziifm9C4ublIhhXKB44PJLlOFk+YAA3S1GxmzK6CpwwJdV1LXM4FH4F6KXKp1aesdk-SZnRgqblY-MgA)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n#### Typing getDerivedStateFromProps\n\nBefore you start using `getDerivedStateFromProps`, please go through the [documentation](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [You Probably Don't Need Derived State](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). Derived State can be implemented using hooks which can also help set up memoization.\n\nHere are a few ways in which you can annotate `getDerivedStateFromProps`\n\n1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it.\n\n```tsx\nclass Comp extends React.Component<Props, State> {\n  static getDerivedStateFromProps(\n    props: Props,\n    state: State\n  ): Partial<State> | null {\n    //\n  }\n}\n```\n\n2. When you want the function's return value to determine your state.\n\n```tsx\nclass Comp extends React.Component<\n  Props,\n  ReturnType<typeof Comp[\"getDerivedStateFromProps\"]>\n> {\n  static getDerivedStateFromProps(props: Props) {}\n}\n```\n\n3. When you want derived state with other state fields and memoization\n\n```tsx\ntype CustomValue = any;\ninterface Props {\n  propA: CustomValue;\n}\ninterface DefinedState {\n  otherStateField: string;\n}\ntype State = DefinedState & ReturnType<typeof transformPropsToState>;\nfunction transformPropsToState(props: Props) {\n  return {\n    savedPropA: props.propA, // save for memoization\n    derivedState: props.propA,\n  };\n}\nclass Comp extends React.PureComponent<Props, State> {\n  constructor(props: Props) {\n    super(props);\n    this.state = {\n      otherStateField: \"123\",\n      ...transformPropsToState(props),\n    };\n  }\n  static getDerivedStateFromProps(props: Props, state: State) {\n    if (isEqual(props.propA, state.savedPropA)) return null;\n    return transformPropsToState(props);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOYAZwFEBHAVxQBs5tcD2IATFHQAWAOnpJWHMuQowAnmCRwAwizoxcANQ4tlAXjgoAdvIDcFYMZhIomdMoAKOMHTgBvCnDhgXAQQAuVXVNEB12PQtyAF9La1t7NGUAESRMKyR+AGUYFBsPLzgIGGFbHLykADFgJHZ+II0oKwBzKNjyBSU4cvzDVPTjTJ7lADJEJBgWKGMAFUUkAB5OpAhMOBgoEzpMaBBnCFcZiGGAPijMFmMMYAhjdc3jbd39w+PcmwAKXwO6IJe6ACUBXI3iIk2mwO83joKAAbpkXoEfC46KJvmA-AAaOAAehxcBh8K40DgICQIAgwAAXnkbsZCt5+LZgPDsu8kEF0aj0X5CtE2hQ0OwhG4VLgwHAkAAPGzGfhuZDoGCiRxTJBi8C3JDWBb-bGnSFwNC3RosDDQL4ov4ooGeEFQugsJRQS0-AFRKHrYT0UQaCpwQx2z3eYqlKDDaq1epwABEAEYAEwAZhjmIZUNEmY2Wx2UD2KKOw1drgB6f5fMKfpgwDQcGaE1STVZEZw+Z+xd+cD1BPZQWGtvTwDWH3ozDY7A7aP82KrSF9cIR-gBQLBUzuxhY7HYHqhq4h2ceubbryLXPdFZiQA)\n\n<!--END-SECTION:class-components-->\n\n<!--START-SECTION:default-props-->\n\n#### You May Not Need `defaultProps`\n\nAs per [this tweet](https://twitter.com/dan_abramov/status/1133878326358171650), defaultProps will eventually be deprecated. You can check the discussions here:\n\n- [Original tweet](https://twitter.com/hswolff/status/1133759319571345408)\n- More info can also be found in [this article](https://medium.com/@matanbobi/react-defaultprops-is-dying-whos-the-contender-443c19d9e7f1)\n\nThe consensus is to use object default values.\n\nFunction Components:\n\n```tsx\ntype GreetProps = { age?: number };\n\nconst Greet = ({ age = 21 }: GreetProps) => // etc\n```\n\nClass Components:\n\n```tsx\ntype GreetProps = {\n  age?: number;\n};\n\nclass Greet extends React.Component<GreetProps> {\n  render() {\n    const { age = 21 } = this.props;\n    /*...*/\n  }\n}\n\nlet el = <Greet age={3} />;\n```\n\n#### Typing `defaultProps`\n\nType inference improved greatly for `defaultProps` in [TypeScript 3.0+](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html), although [some edge cases are still problematic](https://github.com/typescript-cheatsheets/react/issues/61).\n\n**Function Components**\n\n```tsx\n// using typeof as a shortcut; note that it hoists!\n// you can also declare the type of DefaultProps if you choose\n// e.g. https://github.com/typescript-cheatsheets/react/issues/415#issuecomment-841223219\ntype GreetProps = { age: number } & typeof defaultProps;\n\nconst defaultProps = {\n  age: 21,\n};\n\nconst Greet = (props: GreetProps) => {\n  // etc\n};\nGreet.defaultProps = defaultProps;\n```\n\n_[See this in TS Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAOKVYwAKxY6ALxwA3igDmWAFxwAdgFcQAIyxQ4AXzgAyOM1YQCcACZYCyeQBte-VPVwRZqeCbOXrEAXGEi6cCdLgAJgBGABo6dXo6e0d4TixuLzgACjAbGXjuPg9UAEovAD5RXzhKGHkoWTgAHiNgADcCkTScgDpkSTgAeiQFZVVELvVqrrrGiPpMmFaXcytsz2FZtwXbOiA)_\n\nFor **Class components**, there are [a couple ways to do it](https://github.com/typescript-cheatsheets/react/pull/103#issuecomment-481061483) (including using the `Pick` utility type) but the recommendation is to \"reverse\" the props definition:\n\n```tsx\ntype GreetProps = typeof Greet.defaultProps & {\n  age: number;\n};\n\nclass Greet extends React.Component<GreetProps> {\n  static defaultProps = {\n    age: 21,\n  };\n  /*...*/\n}\n\n// Type-checks! No type assertions needed!\nlet el = <Greet age={3} />;\n```\n\n<details>\n<summary><b><code>React.JSX.LibraryManagedAttributes</code> nuance for library authors</b></summary>\n\nThe above implementations work fine for App creators, but sometimes you want to be able to export `GreetProps` so that others can consume it. The problem here is that the way `GreetProps` is defined, `age` is a required prop when it isn't because of `defaultProps`.\n\nThe insight to have here is that [`GreetProps` is the _internal_ contract for your component, not the _external_, consumer facing contract](https://github.com/typescript-cheatsheets/react/issues/66#issuecomment-453878710). You could create a separate type specifically for export, or you could make use of the `React.JSX.LibraryManagedAttributes` utility:\n\n```tsx\n// internal contract, should not be exported out\ntype GreetProps = {\n  age: number;\n};\n\nclass Greet extends Component<GreetProps> {\n  static defaultProps = { age: 21 };\n}\n\n// external contract\nexport type ApparentGreetProps = React.JSX.LibraryManagedAttributes<\n  typeof Greet,\n  GreetProps\n>;\n```\n\nThis will work properly, although hovering over`ApparentGreetProps`may be a little intimidating. You can reduce this boilerplate with the`ComponentProps` utility detailed below.\n\n</details>\n\n#### Consuming Props of a Component with defaultProps\n\nA component with `defaultProps` may seem to have some required props that actually aren't.\n\n##### Problem Statement\n\nHere's what you want to do:\n\n```tsx\ninterface IProps {\n  name: string;\n}\nconst defaultProps = {\n  age: 25,\n};\nconst GreetComponent = ({ name, age }: IProps & typeof defaultProps) => (\n  <div>{`Hello, my name is ${name}, ${age}`}</div>\n);\nGreetComponent.defaultProps = defaultProps;\n\nconst TestComponent = (props: React.ComponentProps<typeof GreetComponent>) => {\n  return <h1 />;\n};\n\n// Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'\nconst el = <TestComponent name=\"foo\" />;\n```\n\n##### Solution\n\nDefine a utility that applies `React.JSX.LibraryManagedAttributes`:\n\n```tsx\ntype ComponentProps<T> = T extends\n  | React.ComponentType<infer P>\n  | React.Component<infer P>\n  ? React.JSX.LibraryManagedAttributes<T, P>\n  : never;\n\nconst TestComponent = (props: ComponentProps<typeof GreetComponent>) => {\n  return <h1 />;\n};\n\n// No error\nconst el = <TestComponent name=\"foo\" />;\n```\n\n[_See this in TS Playground_](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAMImQB2W3MABWJhUAHgAqAPjgBeOOLhYAHjD4ATdNjwwAdJ3ARe-cSyyjg3AlihwB0gD6Yqu-Tz4xzl67cl04cAH44ACkAZQANHQAZYAAjKGQoJgBZZG5kAHMsNQBBGBgoOIBXVTFxABofPzgALjheADdrejoLVSgCPDYASSEIETgAb2r0kCw61AKLDPoAXzpcQ0m4NSxOooAbQWF0OWH-TPG4ACYAVnK6WfpF7mWAcUosGFdDd1k4AApB+uQxysO4LM6r0dnAAGRwZisCAEFZrZCbbb9VAASlk0g+1VEamADUkgwABgAJLAbDYQSogJg-MZwYDoAAkg1GWFmlSZh1mBNmogA9Di8XQUfQHlgni8jLpVustn0BnJpQjZTsWrzeXANsh2gwbstxFhJhK3nIPmAdnUjfw5WIoVgYXBReKuK9+JI0TJpPs4JQYEUoNw4KIABYARjgvN8VwYargADkIIooMQoAslvBSe8JAbns7JTSsDIyAQIBAyOHJDQgA)\n\n#### Misc Discussions and Knowledge\n\n<details>\n<summary><b>Why does <code>React.FC</code> break <code>defaultProps</code>?</b></summary>\n\nYou can check the discussions here:\n\n- https://medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680\n- https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30695\n- https://github.com/typescript-cheatsheets/react/issues/87\n\nThis is just the current state and may be fixed in future.\n\n</details>\n\n<details>\n<summary><b>TypeScript 2.9 and earlier</b></summary>\n\nFor TypeScript 2.9 and earlier, there's more than one way to do it, but this is the best advice we've yet seen:\n\n```ts\ntype Props = Required<typeof MyComponent.defaultProps> & {\n  /* additional props here */\n};\n\nexport class MyComponent extends React.Component<Props> {\n  static defaultProps = {\n    foo: \"foo\",\n  };\n}\n```\n\nOur former recommendation used the `Partial type` feature in TypeScript, which means that the current interface will fulfill a partial version on the wrapped interface. In that way we can extend defaultProps without any changes in the types!\n\n```ts\ninterface IMyComponentProps {\n  firstProp?: string;\n  secondProp: IPerson[];\n}\n\nexport class MyComponent extends React.Component<IMyComponentProps> {\n  public static defaultProps: Partial<IMyComponentProps> = {\n    firstProp: \"default\",\n  };\n}\n```\n\nThe problem with this approach is it causes complex issues with the type inference working with `React.JSX.LibraryManagedAttributes`. Basically it causes the compiler to think that when creating a JSX expression with that component, that all of its props are optional.\n\n[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57) and [here](https://github.com/typescript-cheatsheets/react/issues/61).\n\n</details>\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n<!--END-SECTION:default-props-->\n\n<!--START-SECTION:basic-type-examples-->\n\n#### Typing Component Props\n\nThis is intended as a basic orientation and reference for React developers familiarizing with TypeScript.\n\n#### Basic Prop Types Examples\n\nA list of TypeScript types you will likely use in a React+TypeScript app:\n\n```tsx\ntype AppProps = {\n  message: string;\n  count: number;\n  disabled: boolean;\n  /** array of a type! */\n  names: string[];\n  /** string literals to specify exact string values, with a union type to join them together */\n  status: \"waiting\" | \"success\";\n  /** an object with known properties (but could have more at runtime) */\n  obj: {\n    id: string;\n    title: string;\n  };\n  /** array of objects! (common) */\n  objArr: {\n    id: string;\n    title: string;\n  }[];\n  /** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */\n  obj2: object;\n  /** an interface with no required properties - (NOT COMMON, except for things like `React.Component<{}, State>`) */\n  obj3: {};\n  /** a dict object with any number of properties of the same type */\n  dict1: {\n    [key: string]: MyTypeHere;\n  };\n  dict2: Record<string, MyTypeHere>; // equivalent to dict1\n  /** function that doesn't take or return anything (VERY COMMON) */\n  onClick: () => void;\n  /** function with named prop (VERY COMMON) */\n  onChange: (id: number) => void;\n  /** function type syntax that takes an event (VERY COMMON) */\n  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;\n  /** alternative function type syntax that takes an event (VERY COMMON) */\n  onClick(event: React.MouseEvent<HTMLButtonElement>): void;\n  /** any function as long as you don't invoke it (not recommended) */\n  onSomething: Function;\n  /** an optional prop (VERY COMMON!) */\n  optional?: OptionalType;\n  /** when passing down the state setter function returned by `useState` to a child component. `number` is an example, swap out with whatever the type of your state */\n  setState: React.Dispatch<React.SetStateAction<number>>;\n};\n```\n\n##### `object` as the non-primitive type\n\n`object` is a common source of misunderstanding in TypeScript. It does not mean \"any object\" but rather \"any non-primitive type\", which means it represents anything that is not `number`, `bigint`, `string`, `boolean`, `symbol`, `null` or `undefined`.\n\nTyping \"any non-primitive value\" is most likely not something that you should do much in React, which means you will probably not use `object` much.\n\n##### Empty interface, `{}` and `Object`\n\nAn empty interface, `{}` and `Object` all represent \"any non-nullish value\"—not \"an empty object\" as you might think. [Using these types is a common source of misunderstanding and is not recommended](https://typescript-eslint.io/rules/no-empty-interface/).\n\n```ts\ninterface AnyNonNullishValue {} // equivalent to `type AnyNonNullishValue = {}` or `type AnyNonNullishValue = Object`\n\nlet value: AnyNonNullishValue;\n\n// these are all fine, but might not be expected\nvalue = 1;\nvalue = \"foo\";\nvalue = () => alert(\"foo\");\nvalue = {};\nvalue = { foo: \"bar\" };\n\n// these are errors\nvalue = undefined;\nvalue = null;\n```\n\n#### Useful React Prop Type Examples\n\nRelevant for components that accept other React components as props.\n\n```tsx\nexport declare interface AppProps {\n  children?: React.ReactNode; // best, accepts everything React can render\n  childrenElement: React.JSX.Element; // A single React element\n  style?: React.CSSProperties; // to pass through style props\n  onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target\n  //  more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring\n  props: Props & React.ComponentPropsWithoutRef<\"button\">; // to impersonate all the props of a button element and explicitly not forwarding its ref\n  props2: Props & React.ComponentPropsWithRef<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref\n}\n```\n\n<details>\n<summary><b>Small <code>React.ReactNode</code> edge case before React 18</b></summary>\n\nBefore the [React 18 type updates](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210), this code typechecked but had a runtime error:\n\n```tsx\ntype Props = {\n  children?: React.ReactNode;\n};\n\nfunction Comp({ children }: Props) {\n  return <div>{children}</div>;\n}\nfunction App() {\n  // Before React 18: Runtime error \"Objects are not valid as a React child\"\n  // After React 18: Typecheck error \"Type '{}' is not assignable to type 'ReactNode'\"\n  return <Comp>{{}}</Comp>;\n}\n```\n\nThis is because `ReactNode` includes `ReactFragment` which allowed type `{}` before React 18.\n\n[Thanks @pomle for raising this.](https://github.com/typescript-cheatsheets/react/issues/357)\n\n</details>\n\n<details>\n <summary><b>React.JSX.Element vs React.ReactNode?</b></summary>\n\nQuote [@ferdaber](https://github.com/typescript-cheatsheets/react/issues/57): A more technical explanation is that a valid React node is not the same thing as what is returned by `React.createElement`. Regardless of what a component ends up rendering, `React.createElement` always returns an object, which is the `React.JSX.Element` interface, but `React.ReactNode` is the set of all possible return values of a component.\n\n- `React.JSX.Element` -> Return value of `React.createElement`\n- `React.ReactNode` -> Return value of a component\n\n</details>\n\n[More discussion: Where ReactNode does not overlap with React.JSX.Element](https://github.com/typescript-cheatsheets/react/issues/129)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n#### Types or Interfaces?\n\nYou can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use?\n\n##### TL;DR\n\nUse Interface until You Need Type - [orta](https://twitter.com/orta/status/1356129195835973632?s=20).\n\n##### More Advice\n\nHere's a helpful rule of thumb:\n\n- always use `interface` for public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via _declaration merging_ if some definitions are missing.\n\n- consider using `type` for your React Component Props and State, for consistency and because it is more constrained.\n\nYou can read more about the reasoning behind this rule of thumb in [Interface vs Type alias in TypeScript 2.7](https://medium.com/@martin_hotell/interface-vs-type-alias-in-typescript-2-7-2a8f1777af4c).\n\nThe TypeScript Handbook now also includes guidance on [Differences Between Type Aliases and Interfaces](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces).\n\n> Note: At scale, there are performance reasons to prefer interfaces ([see official Microsoft notes on this](https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections)) but [take this with a grain of salt](https://news.ycombinator.com/item?id=25201887)\n\nTypes are useful for union types (e.g. `type MyType = TypeA | TypeB`) whereas Interfaces are better for declaring dictionary shapes and then `implementing` or `extending` them.\n\n##### Useful table for Types vs Interfaces\n\nIt's a nuanced topic, don't get too hung up on it. Here's a handy table:\n\n| Aspect                                          | Type | Interface |\n| ----------------------------------------------- | :--: | :-------: |\n| Can describe functions                          |  ✅  |    ✅     |\n| Can describe constructors                       |  ✅  |    ✅     |\n| Can describe tuples                             |  ✅  |    ✅     |\n| Interfaces can extend it                        |  ⚠️  |    ✅     |\n| Classes can extend it                           |  🚫  |    ✅     |\n| Classes can implement it (`implements`)         |  ⚠️  |    ✅     |\n| Can intersect another one of its kind           |  ✅  |    ⚠️     |\n| Can create a union with another one of its kind |  ✅  |    🚫     |\n| Can be used to create mapped types              |  ✅  |    🚫     |\n| Can be mapped over with mapped types            |  ✅  |    ✅     |\n| Expands in error messages and logs              |  ✅  |    🚫     |\n| Can be augmented                                |  🚫  |    ✅     |\n| Can be recursive                                |  ⚠️  |    ✅     |\n\n⚠️ In some cases\n\n(source: [Karol Majewski](https://twitter.com/karoljmajewski/status/1082413696075382785))\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n<!--END-SECTION:basic-type-examples-->\n\n<!--START-SECTION:get-derived-state-from-props-->\n\n## getDerivedStateFromProps\n\nBefore you start using `getDerivedStateFromProps`, please go through the [documentation](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [You Probably Don't Need Derived State](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). Derived State can be easily achieved using hooks which can also help set up memoization easily.\n\nHere are a few ways in which you can annotate `getDerivedStateFromProps`\n\n1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it.\n\n```tsx\nclass Comp extends React.Component<Props, State> {\n  static getDerivedStateFromProps(\n    props: Props,\n    state: State\n  ): Partial<State> | null {\n    //\n  }\n}\n```\n\n2. When you want the function's return value to determine your state.\n\n```tsx\nclass Comp extends React.Component<\n  Props,\n  ReturnType<typeof Comp[\"getDerivedStateFromProps\"]>\n> {\n  static getDerivedStateFromProps(props: Props) {}\n}\n```\n\n3. When you want derived state with other state fields and memoization\n\n```tsx\ntype CustomValue = any;\ninterface Props {\n  propA: CustomValue;\n}\ninterface DefinedState {\n  otherStateField: string;\n}\ntype State = DefinedState & ReturnType<typeof transformPropsToState>;\nfunction transformPropsToState(props: Props) {\n  return {\n    savedPropA: props.propA, // save for memoization\n    derivedState: props.propA,\n  };\n}\nclass Comp extends React.PureComponent<Props, State> {\n  constructor(props: Props) {\n    super(props);\n    this.state = {\n      otherStateField: \"123\",\n      ...transformPropsToState(props),\n    };\n  }\n  static getDerivedStateFromProps(props: Props, state: State) {\n    if (isEqual(props.propA, state.savedPropA)) return null;\n    return transformPropsToState(props);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOYAZwFEBHAVxQBs5tcD2IATFHQAWAOnpJWHMuQowAnmCRwAwizoxcANQ4tlAXjgoAdvIDcFYMZhIomdMoAKOMHTgBvCnDhgXAQQAuVXVNEB12PQtyAF9La1t7NGUAESRMKyR+AGUYFBsPLzgIGGFbHLykADFgJHZ+II0oKwBzKNjyBSU4cvzDVPTjTJ7lADJEJBgWKGMAFUUkAB5OpAhMOBgoEzpMaBBnCFcZiGGAPijMFmMMYAhjdc3jbd39w+PcmwAKXwO6IJe6ACUBXI3iIk2mwO83joKAAbpkXoEfC46KJvmA-AAaOAAehxcBh8K40DgICQIAgwAAXnkbsZCt5+LZgPDsu8kEF0aj0X5CtE2hQ0OwhG4VLgwHAkAAPGzGfhuZDoGCiRxTJBi8C3JDWBb-bGnSFwNC3RosDDQL4ov4ooGeEFQugsJRQS0-AFRKHrYT0UQaCpwQx2z3eYqlKDDaq1epwABEAEYAEwAZhjmIZUNEmY2Wx2UD2KKOw1drgB6f5fMKfpgwDQcGaE1STVZEZw+Z+xd+cD1BPZQWGtvTwDWH3ozDY7A7aP82KrSF9cIR-gBQLBUzuxhY7HYHqhq4h2ceubbryLXPdFZiQA)\n\n<!--END-SECTION:get-derived-state-from-props-->\n\n<!--START-SECTION:forms-and-events-->\n\n#### Forms and Events\n\nIf performance is not an issue (and it usually isn't!), inlining handlers is easiest as you can just use [type inference and contextual typing](https://www.typescriptlang.org/docs/handbook/type-inference.html#contextual-typing):\n\n```tsx\nconst el = (\n  <button\n    onClick={(event) => {\n      /* event will be correctly typed automatically! */\n    }}\n  />\n);\n```\n\nBut if you need to define your event handler separately, IDE tooling really comes in handy here, as the @type definitions come with a wealth of typing. Type what you are looking for and usually the autocomplete will help you out. Here is what it looks like for an `onChange` for a form event:\n\n```tsx\ntype State = {\n  text: string;\n};\nclass App extends React.Component<Props, State> {\n  state = {\n    text: \"\",\n  };\n\n  // typing on RIGHT hand side of =\n  onChange = (e: React.FormEvent<HTMLInputElement>): void => {\n    this.setState({ text: e.currentTarget.value });\n  };\n  render() {\n    return (\n      <div>\n        <input type=\"text\" value={this.state.text} onChange={this.onChange} />\n      </div>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2KA9Drg8IcMDjB1tcblwBccOjCjAeAcwDcmlRQB8W8ovso3HAAvL6KilYwtgBE0R7ulH5wepYAnmBOznAQPIgAkgDiABIAKnAAFij8dsB8SNmYIZo5YpUu9aEAFEi2QhgiAGLQIACiAG4ysqUAsgAyeTxgAK4wI9RIIDJeAJS2YxC1IT5KFjDlwHQidEgwAMowgUidSpacUewiaEtQRDwwJSgoM4biIxihqEt6iptglFCpYXBfnUoJ1tmFwkQYN9cp0LIpZHxgGMvHjwrInMt4DB0khgtFItE4GCIbSlGcLlcHtwRJEVNkeK0qsDgmzzpcWm1gXydCSkuE4LIdITiRYYR4KCogA)\n\nInstead of typing the arguments and return values with `React.FormEvent<>` and `void`, you may alternatively apply types to the event handler itself (_contributed by @TomasHubelbauer_):\n\n```tsx\n  // typing on LEFT hand side of =\n  onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {\n    this.setState({text: e.currentTarget.value})\n  }\n```\n\n<details>\n\n<summary><b>Why two ways to do the same thing?</b></summary>\n\nThe first method uses an inferred method signature `(e: React.FormEvent<HTMLInputElement>): void` and the second method enforces a type of the delegate provided by `@types/react`. So `React.ChangeEventHandler<>` is simply a \"blessed\" typing by `@types/react`, whereas you can think of the inferred method as more... _artisanally hand-rolled_. Either way it's a good pattern to know. [See our Github PR for more](https://github.com/typescript-cheatsheets/react/pull/24).\n\n</details>\n\n> Starting with React v19.2.10 `FormEvent` and `FormEventHandler` are deprecated and should be replaced with `SubmitEvent` and `SubmitEventHandler`. The older event types will still work but trigger a deprecation message.\n\n**Typing onSubmit, with Uncontrolled components in a Form**\n\nIf you don't quite care about the type of the event, you can just use `React.SyntheticEvent`. If your target form has custom named inputs that you'd like to access, you can use a type assertion:\n\n```tsx\n<form\n  ref={formRef}\n  onSubmit={(e: React.SyntheticEvent) => {\n    e.preventDefault();\n    const target = e.target as typeof e.target & {\n      email: { value: string };\n      password: { value: string };\n    };\n    const email = target.email.value; // typechecks!\n    const password = target.password.value; // typechecks!\n    // etc...\n  }}\n>\n  <div>\n    <label>\n      Email:\n      <input type=\"email\" name=\"email\" />\n    </label>\n  </div>\n  <div>\n    <label>\n      Password:\n      <input type=\"password\" name=\"password\" />\n    </label>\n  </div>\n  <div>\n    <input type=\"submit\" value=\"Log in\" />\n  </div>\n</form>\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtCAOwGctoRlM4BeRYmAOgFc6kLABQBKClVoM4AMSbs4o9gD4FFOHAA8mJmrhFMbAN7aozJJgC+u2gGVeAIxDAYRoUgBcndDxsBPGjAAFkgwwGgAogBuSAEiynCGuupI3GBE0QEAIuYovAA2MKIA3Elw1PTwMChQAOYh8ilVtfUodHAwvmBIEKyN1XXwAGQJpckgKMB5noZwkSh5vB5wDFDANDVwFiXk6rtwYK10AO7QACbTs-OLnitrG1ulDzu75VJI45PyTQPc7xN53DmCyQRTgAHowe1Okg0ME0ABrOgAQlKr3gBzoxzOX36IVShxOUFOgKuIPBkI6XVhMMRKOe6ghcBCaG4rN0Fis5CUug0p2AkW59M0eRQ9iQeUFe3U4Q+U1GmjWYF4lWhbAARH9Jmq4DQUCAkOrNXltWDJbsNGCRWKJTywXyBTz7Wb1BoreLnbsAAoEs7ueUaRXKqFddUYrFE7W6-Whn0R8Eei1um3PC1Ox38hOBlUhtV0BxOGDaoGLdUAGQgGzWJrNqYzFAtJhAgpEQA)\n\nOf course, if you're making any sort of significant form, [you should use Formik](https://jaredpalmer.com/formik) or [React Hook Form](https://react-hook-form.com/), which are written in TypeScript.\n\n##### List of event types\n\n| Event Type       | Description                                                                                                                                                                                                                                                            |\n| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| AnimationEvent   | CSS Animations.                                                                                                                                                                                                                                                        |\n| ChangeEvent      | Changing the value of `<input>`, `<select>` and `<textarea>` element.                                                                                                                                                                                                  |\n| ClipboardEvent   | Using copy, paste and cut events.                                                                                                                                                                                                                                      |\n| CompositionEvent | Events that occur due to the user indirectly entering text (e.g. depending on Browser and PC setup, a popup window may appear with additional characters if you e.g. want to type Japanese on a US Keyboard)                                                           |\n| DragEvent        | Drag and drop interaction with a pointer device (e.g. mouse).                                                                                                                                                                                                          |\n| FocusEvent       | Event that occurs when elements gets or loses focus.                                                                                                                                                                                                                   |\n| FormEvent        | Event that occurs whenever a form or form element gets/loses focus, a form element value is changed or the form is submitted.                                                                                                                                          |\n| InvalidEvent     | Fired when validity restrictions of an input fails (e.g `<input type=\"number\" max=\"10\">` and someone would insert number 20).                                                                                                                                          |\n| KeyboardEvent    | User interaction with the keyboard. Each event describes a single key interaction.                                                                                                                                                                                     |\n| InputEvent       | Event that occurs before the value of `<input>`, `<select>` and `<textarea>` changes.                                                                                                                                                                                  |\n| MouseEvent       | Events that occur due to the user interacting with a pointing device (e.g. mouse)                                                                                                                                                                                      |\n| PointerEvent     | Events that occur due to user interaction with a variety pointing of devices such as mouse, pen/stylus, a touchscreen and which also supports multi-touch. Unless you develop for older browsers (IE10 or Safari 12), pointer events are recommended. Extends UIEvent. |\n| TouchEvent       | Events that occur due to the user interacting with a touch device. Extends UIEvent.                                                                                                                                                                                    |\n| TransitionEvent  | CSS Transition. Not fully browser supported. Extends UIEvent                                                                                                                                                                                                           |\n| UIEvent          | Base Event for Mouse, Touch and Pointer events.                                                                                                                                                                                                                        |\n| WheelEvent       | Scrolling on a mouse wheel or similar input device. (Note: `wheel` event should not be confused with the `scroll` event)                                                                                                                                               |\n| SyntheticEvent   | The base event for all above events. Should be used when unsure about event type                                                                                                                                                                                       |\n\n<!--END-SECTION:forms-and-events-->\n\n<!--START-SECTION:context-->\n\n#### Context\n\n#### Basic example\n\nHere's a basic example of creating a context containing the active theme.\n\n```tsx\nimport { createContext } from \"react\";\n\ntype ThemeContextType = \"light\" | \"dark\";\n\nconst ThemeContext = createContext<ThemeContextType>(\"light\");\n```\n\nWrap the components that need the context with a context provider:\n\n```tsx\nimport { useState } from \"react\";\n\nconst App = () => {\n  const [theme, setTheme] = useState<ThemeContextType>(\"light\");\n\n  return (\n    <ThemeContext.Provider value={theme}>\n      <MyComponent />\n    </ThemeContext.Provider>\n  );\n};\n```\n\nCall `useContext` to read and subscribe to the context.\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const theme = useContext(ThemeContext);\n\n  return <p>The current theme is {theme}.</p>;\n};\n```\n\n#### Without default context value\n\nIf you don't have any meaningful default value, specify `null`:\n\n```tsx\nimport { createContext } from \"react\";\n\ninterface CurrentUserContextType {\n  username: string;\n}\n\nconst CurrentUserContext = createContext<CurrentUserContextType | null>(null);\n```\n\n```tsx\nconst App = () => {\n  const [currentUser, setCurrentUser] = useState<CurrentUserContextType>({\n    username: \"filiptammergard\",\n  });\n\n  return (\n    <CurrentUserContext.Provider value={currentUser}>\n      <MyComponent />\n    </CurrentUserContext.Provider>\n  );\n};\n```\n\nNow that the type of the context can be `null`, you'll notice that you'll get a `'currentUser' is possibly 'null'` TypeScript error if you try to access the `username` property. You can use optional chaining to access `username`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const currentUser = useContext(CurrentUserContext);\n\n  return <p>Name: {currentUser?.username}.</p>;\n};\n```\n\nHowever, it would be preferable to not have to check for `null`, since we know that the context won't be `null`. One way to do that is to provide a custom hook to use the context, where an error is thrown if the context is not provided:\n\n```tsx\nimport { createContext } from \"react\";\n\ninterface CurrentUserContextType {\n  username: string;\n}\n\nconst CurrentUserContext = createContext<CurrentUserContextType | null>(null);\n\nconst useCurrentUser = () => {\n  const currentUserContext = useContext(CurrentUserContext);\n\n  if (!currentUserContext) {\n    throw new Error(\n      \"useCurrentUser has to be used within <CurrentUserContext.Provider>\"\n    );\n  }\n\n  return currentUserContext;\n};\n```\n\nUsing a runtime type check in this will has the benefit of printing a clear error message in the console when a provider is not wrapping the components properly. Now it's possible to access `currentUser.username` without checking for `null`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const currentUser = useCurrentUser();\n\n  return <p>Username: {currentUser.username}.</p>;\n};\n```\n\n##### Type assertion as an alternative\n\nAnother way to avoid having to check for `null` is to use type assertion to tell TypeScript you know the context is not `null`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const currentUser = useContext(CurrentUserContext);\n\n  return <p>Name: {currentUser!.username}.</p>;\n};\n```\n\nAnother option is to use an empty object as default value and cast it to the expected context type:\n\n```tsx\nconst CurrentUserContext = createContext<CurrentUserContextType>(\n  {} as CurrentUserContextType\n);\n```\n\nYou can also use non-null assertion to get the same result:\n\n```tsx\nconst CurrentUserContext = createContext<CurrentUserContextType>(null!);\n```\n\nWhen you don't know what to choose, prefer runtime checking and throwing over type asserting.\n\n<!--END-SECTION:context-->\n\n<!--START-SECTION:forward-create-ref-->\n\n#### forwardRef/createRef\n\nFor `useRef`, check the [Hooks section](/docs/basic/getting-started/hooks#useref).\n\n#### Ref as a Prop (Recommended for React 19+)\n\nIn React 19+, you can access `ref` directly as a prop in function components - no `forwardRef` wrapper needed.\n\n##### Option 1: Inherit all props from a native element\n\nUse `ComponentPropsWithRef` to inherit all props from a native element.\n\n```tsx\nimport { ComponentPropsWithRef, useRef } from \"react\";\n\nfunction MyInput(props: ComponentPropsWithRef<\"input\">) {\n  return <input {...props} />;\n}\n\n// Usage in parent component\nfunction Parent() {\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  return <MyInput ref={inputRef} placeholder=\"Type here...\" />;\n}\n```\n\n##### Option 2: Explicit typing\n\nIf you have custom props and want fine-grained control, you can explicitly type the ref:\n\n```tsx\nimport { Ref, useRef } from \"react\";\n\ninterface MyInputProps {\n  placeholder: string;\n  ref: Ref<HTMLInputElement>;\n}\n\nfunction MyInput(props: MyInputProps) {\n  return <input {...props} />;\n}\n\n// Usage in parent component\nfunction Parent() {\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  return <MyInput ref={inputRef} placeholder=\"Type here...\" />;\n}\n```\n\n**Read more**: [Wrapping/Mirroring a HTML Element](/docs/advanced/patterns_by_usecase#wrappingmirroring-a-html-element)\n\n#### Legacy Approaches (Pre-React 19)\n\n##### forwardRef\n\nFor React 18 and earlier, use `forwardRef`:\n\n```tsx\nimport { forwardRef, ReactNode } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n  type: \"submit\" | \"button\";\n}\nexport type Ref = HTMLButtonElement;\n\nexport const FancyButton = forwardRef<Ref, Props>((props, ref) => (\n  <button ref={ref} className=\"MyClassName\" type={props.type}>\n    {props.children}\n  </button>\n));\n```\n\n<details>\n<summary><b>Side note: the <code>ref</code> you get from <code>forwardRef</code> is mutable so you can assign to it if needed.</b></summary>\n\nThis was done [on purpose](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43265/). You can make it immutable if you have to - assign `React.Ref` if you want to ensure nobody reassigns it:\n\n```tsx\nimport { forwardRef, ReactNode, Ref } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n  type: \"submit\" | \"button\";\n}\n\nexport const FancyButton = forwardRef(\n  (\n    props: Props,\n    ref: Ref<HTMLButtonElement> // <-- explicit immutable ref type\n  ) => (\n    <button ref={ref} className=\"MyClassName\" type={props.type}>\n      {props.children}\n    </button>\n  )\n);\n```\n\n</details>\n\nIf you need to grab props from a component that forwards refs, use [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770).\n\n##### createRef\n\n`createRef` is mostly used for class components. Function components typically rely on `useRef` instead.\n\n```tsx\nimport { createRef, PureComponent } from \"react\";\n\nclass CssThemeProvider extends PureComponent<Props> {\n  private rootRef = createRef<HTMLDivElement>();\n\n  render() {\n    return <div ref={this.rootRef}>{this.props.children}</div>;\n  }\n}\n```\n\n#### Generic Components with Refs\n\nGeneric components typically require manual ref handling since their generic nature prevents automatic type inference. Here are the main approaches:\n\nRead more context in [this article](https://fettblog.eu/typescript-react-generic-forward-refs/).\n\n##### Option 1: Wrapper Component\n\nThe most straightforward approach is to manually handle refs through props:\n\n```tsx\ninterface ClickableListProps<T> {\n  items: T[];\n  onSelect: (item: T) => void;\n  mRef?: React.Ref<HTMLUListElement> | null;\n}\n\nexport function ClickableList<T>(props: ClickableListProps<T>) {\n  return (\n    <ul ref={props.mRef}>\n      {props.items.map((item, i) => (\n        <li key={i}>\n          <button onClick={() => props.onSelect(item)}>Select</button>\n          {item}\n        </li>\n      ))}\n    </ul>\n  );\n}\n```\n\n##### Option 2: Redeclare forwardRef\n\nFor true `forwardRef` behavior with generics, extend the module declaration:\n\n```tsx\n// Redeclare forwardRef to support generics\ndeclare module \"react\" {\n  function forwardRef<T, P = {}>(\n    render: (props: P, ref: React.Ref<T>) => React.ReactElement | null\n  ): (props: P & React.RefAttributes<T>) => React.ReactElement | null;\n}\n\n// Now you can use forwardRef with generics normally\nimport { forwardRef, ForwardedRef } from \"react\";\n\ninterface ClickableListProps<T> {\n  items: T[];\n  onSelect: (item: T) => void;\n}\n\nfunction ClickableListInner<T>(\n  props: ClickableListProps<T>,\n  ref: ForwardedRef<HTMLUListElement>\n) {\n  return (\n    <ul ref={ref}>\n      {props.items.map((item, i) => (\n        <li key={i}>\n          <button onClick={() => props.onSelect(item)}>Select</button>\n          {item}\n        </li>\n      ))}\n    </ul>\n  );\n}\n\nexport const ClickableList = forwardRef(ClickableListInner);\n```\n\n##### Option 3: Call Signature\n\nIf you need both generic support and proper forwardRef behavior with full type inference, you can use the call signature:\n\n```tsx\n// Add to your type definitions (e.g. in `index.d.ts` file)\ninterface ForwardRefWithGenerics extends React.FC<WithForwardRefProps<Option>> {\n  <T extends Option>(props: WithForwardRefProps<T>): ReturnType<\n    React.FC<WithForwardRefProps<T>>\n  >;\n}\n\nexport const ClickableListWithForwardRef: ForwardRefWithGenerics =\n  forwardRef(ClickableList);\n```\n\nCredits: [https://stackoverflow.com/a/73795494](https://stackoverflow.com/a/73795494)\n\n:::note\nOption 1 is usually sufficient and clearer. Use Option 2 when you specifically need `forwardRef` behavior. Use Option 3 for advanced library scenarios requiring both generics and full forwardRef type inference.\n:::\n\n#### Additional Resources\n\n- [React refs with TypeScript](https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315)\n- [Conditional rendering with forwardRef](https://github.com/typescript-cheatsheets/react/issues/167)\n\n---\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new)\n\n<!--END-SECTION:forward-create-ref-->\n\n<!--START-SECTION:portals-->\n\n#### Portals\n\nUsing `ReactDOM.createPortal`:\n\n```tsx\nconst modalRoot = document.getElementById(\"modal-root\") as HTMLElement;\n// assuming in your html file has a div with id 'modal-root';\n\nexport class Modal extends React.Component<{ children?: React.ReactNode }> {\n  el: HTMLElement = document.createElement(\"div\");\n\n  componentDidMount() {\n    modalRoot.appendChild(this.el);\n  }\n\n  componentWillUnmount() {\n    modalRoot.removeChild(this.el);\n  }\n\n  render() {\n    return ReactDOM.createPortal(this.props.children, this.el);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWRYmAEQHkBZObXAo9GAWgBNcZchTQQAdgGd4ICHxQAbBBAjwAvHAFoAriCRiYAOgDmSGAFF5SXfoBCATwCSfABQAiGXPk8cK1wEo4FAk4AAkAFWYAGQsrPRgAbgoAeiTAiQkdYDEjOCy4OwgtKDgACxgQeTZgS1KgwI1gADc4AHdgGBLcvgIPBW9lGHxE4XIkAA9qeDR5IODmWQU4cZg9PmDkbgMAYVxIMTi4AG8KOCX5AC5QiOjLazUNCG07gzQuFZi7tz4m-2GTuFE4HEcXowD48y0+mcAWO5FOp16igGBhQYDAqy2JWqLg6wAkBiQ8j8w1OAF8KP9AXs4gB1aryACqYhkkJg0KO-wRCyRKgMRBkjSQmOxzlx+MJxP+5JGpyIYj4SCg7Nh8LgRBgRTEtG4TGYLzeSAACtAYApRVj8WAcGB8WgsfI+HKADRwMUEokkuDS0lAA)\n\n<details>\n  <summary><b>Using hooks</b></summary>\n\nSame as above but using hooks\n\n```tsx\nimport { useEffect, useRef, ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\nconst modalRoot = document.querySelector(\"#modal-root\") as HTMLElement;\n\ntype ModalProps = {\n  children: ReactNode;\n};\n\nfunction Modal({ children }: ModalProps) {\n  // create div element only once using ref\n  const elRef = useRef<HTMLDivElement | null>(null);\n  if (!elRef.current) elRef.current = document.createElement(\"div\");\n\n  useEffect(() => {\n    const el = elRef.current!; // non-null assertion because it will never be null\n    modalRoot.appendChild(el);\n    return () => {\n      modalRoot.removeChild(el);\n    };\n  }, []);\n\n  return createPortal(children, elRef.current);\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzkgKIBmZSG2RSyZ2y6MAchACZJwC+cZUEEHADkUVBmEBYAFChIsXHDRiUMJAAVoMFABsefAUNHiYAWnaCp0mQHobcFIUL4QwAHYBzOO7gBPCPhQcAAWMCB6ZMA6XMGODnDswABucADuwDDB3uwiIBy6pgIQMMIA3DJoEG6E8HnsuggQxXAAvAkQaC5IbjAAdACO+EhQvgDKSNEY0AAUAEQAxHUFRTCzAJQOhHAAEgAqALIAMiTRIN0w5dbSML5gXPv5OuoCYFttODJwSsFR7GJuAC5ECY2JxLtxLjIyPg3BhgFU4A96jppng0D8dH9ujwgUjdM8IK8Nh9pF87EoVGoEsk4BMkGcenAqjpfEzYVwiO4vGIyJ8lFUarSdPRWgRiPQADx7I4AEWSJ3p5zgAB84G58DodAA+abqzVrS5fYBkODTACEE3ovU6UH+MA2lqQZGtgTtoosnQZfWUqDUCq9c0SSXWkNJYtIFCoMGm0w2LS1uD5X0q1XgE1FjudNrtZtKcHJbiqpj1ekcxFg8LccAARlQULRvPB0pq1UgksMa1wS0m4EthU0+igwHc3OwAMIY9jTCYGntiGCBKux1oJklfde9x6NYq9MR5dsT37TnSzsNfCF87jYADaAF1T3z54uKb6NFpdNN0b9-thMy7becp7cDIIHSOSRAoB4SCgdCsIwJWcAAILDsua78qmcDXoQwQQKkeI6NgxAwKMOF4Y8t6ikwGC9LQozaGo0xkLoxCnl8T5QEuPYSkGWo9mS9j+PgSgoFWzEQHAYD4PAmTAFsPiCUENSqMAaAhGEERRNBZ7rtxNLAOwLSzH2hQDrMWoSjYPF8bg2G4fhcAAGQOaa1lfBK+G8dpG5uUGrneTUvjRC0OBod5YXUoQYA6CgvhArMHhQPpsyYH5YVRegSAAJJqCAhBxWg5zDMlqXecESDAB4oRxQAjAADLVSTBMVXnhV86TsJkQLCHVDXBMIKUta11boAA1glASjnFUAeMN0y1Zg82Lb01VrM1rVhQAXplo5IAAHkCACcB0Det67cMBg3rp5p1fJlwhCCgm7ImaOCzHAswXTdcAStWUkwAiAVBSFw1oGNAgwuwcVgEOvgoKkPxgB9vBVGOOgqSNwXLvGcBESRdmPIxzFIGs3BamgOgQMQFm-TA-1uNd60WVZl0WR51kk9ZP1-QiKNo6DmNxgmuOkfh0wwFAQwk1qtmpIijzU9z9PWeSYiChAJoKQ4w5cZZyQM2sMjcEAA)\n\n</details>\n\nModal Component Usage Example:\n\n```tsx\nimport { useState } from \"react\";\n\nfunction App() {\n  const [showModal, setShowModal] = useState(false);\n\n  return (\n    <div>\n      // you can also put this in your static html file\n      <div id=\"modal-root\"></div>\n      {showModal && (\n        <Modal>\n          <div\n            style={{\n              display: \"grid\",\n              placeItems: \"center\",\n              height: \"100vh\",\n              width: \"100vh\",\n              background: \"rgba(0,0,0,0.1)\",\n              zIndex: 99,\n            }}\n          >\n            I'm a modal!{\" \"}\n            <button\n              style={{ background: \"papyawhip\" }}\n              onClick={() => setShowModal(false)}\n            >\n              close\n            </button>\n          </div>\n        </Modal>\n      )}\n      <button onClick={() => setShowModal(true)}>show Modal</button>\n      // rest of your app\n    </div>\n  );\n}\n```\n\n<details>\n\n<summary><b>Context of Example</b></summary>\n\nThis example is based on the [Event Bubbling Through Portal](https://reactjs.org/docs/portals.html#event-bubbling-through-portals) example of React docs.\n\n</details>\n\n<!--END-SECTION:portals-->\n\n<!--START-SECTION:error-boundaries-->\n\n#### Error Boundaries\n\n##### Option 1: Using react-error-boundary\n\n[React-error-boundary](https://github.com/bvaughn/react-error-boundary) - is a lightweight package ready to use for this scenario with TS support built-in.\nThis approach also lets you avoid class components that are not that popular anymore.\n\n##### Option 2: Writing your custom error boundary component\n\nIf you don't want to add a new npm package for this, you can also write your own `ErrorBoundary` component.\n\n```jsx\nimport React, { Component, ErrorInfo, ReactNode } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n}\n\ninterface State {\n  hasError: boolean;\n}\n\nclass ErrorBoundary extends Component<Props, State> {\n  public state: State = {\n    hasError: false\n  };\n\n  public static getDerivedStateFromError(_: Error): State {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true };\n  }\n\n  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n    console.error(\"Uncaught error:\", error, errorInfo);\n  }\n\n  public render() {\n    if (this.state.hasError) {\n      return <h1>Sorry.. there was an error</h1>;\n    }\n\n    return this.props.children;\n  }\n}\n\nexport default ErrorBoundary;\n\n```\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n<!--END-SECTION:error-boundaries-->\n\n<!--START-SECTION:concurrent-->\n\n#### Concurrent React/React Suspense\n\n_Not written yet._ watch <https://github.com/sw-yx/fresh-async-react> for more on React Suspense and Time Slicing.\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n<!--END-SECTION:concurrent-->\n\n<!--START-SECTION:types-->\n\n### Troubleshooting Handbook: Types\n\n> ⚠️ Have you read [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ?) Your answer might be there!\n\nFacing weird type errors? You aren't alone. This is the hardest part of using TypeScript with React. Be patient - you are learning a new language after all. However, the more you get good at this, the less time you'll be working _against_ the compiler and the more the compiler will be working _for_ you!\n\nTry to avoid typing with `any` as much as possible to experience the full benefits of TypeScript. Instead, let's try to be familiar with some of the common strategies to solve these issues.\n\n#### Union Types and Type Guarding\n\nUnion types are handy for solving some of these typing problems:\n\n```tsx\nclass App extends React.Component<\n  {},\n  {\n    count: number | null; // like this\n  }\n> {\n  state = {\n    count: null,\n  };\n  render() {\n    return <div onClick={() => this.increment(1)}>{this.state.count}</div>;\n  }\n  increment = (amt: number) => {\n    this.setState((state) => ({\n      count: (state.count || 0) + amt,\n    }));\n  };\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2K0EAK48YALjg89IAEZIocAD6m91agG44AejdxqwANZI4MAAWwHSaKhQAfFrkinQwKNxwALzRijr6hiZmTmHOmkT81gAUAJSpaUQwelA8cLJ8wABucBA8Yt5oPklKpclRQSEiwDxoRCAyRQCMJSoRSgN0InEJSCK6BjAqsm4NjRF5MXDhh8OjSOOGyXBFKCDGDpbWZUlRStoBwYt0SDAAyvHcIrLRIva5vQ5pODrTLXYGraHwWz2AAMZQA1HBbjB3ioSiUDooVAcVEA)\n\n**Type Guarding**: Sometimes Union Types solve a problem in one area but create another downstream. If `A` and `B` are both object types, `A | B` means \"either A or B\" (not both at once - that would be an intersection type `A & B`). TypeScript will only let you access properties that exist on both types unless you use type guards to narrow the type. Learn how to write checks, guards, and assertions (also see the Conditional Rendering section below). For example:\n\n```ts\ninterface Admin {\n  role: string;\n}\ninterface User {\n  email: string;\n}\n\n// Method 1: use `in` keyword\nfunction redirect(user: Admin | User) {\n  if (\"role\" in user) {\n    // use the `in` operator for typeguards since TS 2.7+\n    routeToAdminPage(user.role);\n  } else {\n    routeToHomePage(user.email);\n  }\n}\n\n// Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enough\nfunction isAdmin(user: Admin | User): user is Admin {\n  return (user as any).role !== undefined;\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoC4AOxiSk3STgEEATEGuAbwrjhwAbJAC44AZxhQaAcwDcFAL5Va9RmmYBVcfR584SECmCCxk6dXlKKFTAFdqGYBGoCIdugBUI7TtQAKKDJIABTiwDLUwJjA9ACUeuT80XBhEVExugC8OQR2OlAIEML4CbxJ-AJIMHZQrvi+NGQVinDWlOT2jjDOrjgeSN4AErhIgcFpkdGxUGX6KZMZM3A5WQSGxoKliZVVNXUEIyBIYEFIzfzK5FcUAPS3cACy1QAWEGxwAIxi+cwABjQ-nAANZIACeAHdoGxbA4nC4qmxgEQMCFflAxI1XAAfODaeI7ODREIAIiESBJRNc6LKcHucF+cBgL3+gLgEDA9BQMGgcEwvJgYM5MjsKCgbHEEhoGjgngAynAAEwAOgA7ABqfT8fpeHwcGjjULo5XkuIKFoGQQ6Qna9y6o5jM5ogrKjYmM36K43cj057M95KsRofI8vCCzlwEVitgAGjgbAgSElzOY4hQxyZL1kVPZgjYunlcAAbvRwi5JbyISyiHAAdQgcBxLQDNR3DIXrDur0ieIsc76Jj9Ti8QU4j8Cj3WEPCUR9q5+1A4ChJShqGC4ibiswAIS5Bz5mLUJAw65AA)\n\nMethod 2 is also known as [User-Defined Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) and can be really handy for readable code. This is how TS itself refines types with `typeof` and `instanceof`.\n\nIf you need `if...else` chains or the `switch` statement instead, it should \"just work\", but look up [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions) if you need help. (See also: [Basarat's writeup](https://basarat.gitbook.io/typescript/type-system/discriminated-unions)). This is handy in typing reducers for `useReducer` or Redux.\n\n#### Optional Types\n\nIf a component has an optional prop, add a question mark and assign during destructure (or use defaultProps).\n\n```tsx\nclass MyComponent extends React.Component<{\n  message?: string; // like this\n}> {\n  render() {\n    const { message = \"default\" } = this.props;\n    return <div>{message}</div>;\n  }\n}\n```\n\nYou can also use a `!` character to assert that something is not undefined, but this is not encouraged.\n\n_Something to add? [File an issue](https://github.com/typescript-cheatsheets/react/issues/new) with your suggestions!_\n\n#### Enum Types\n\n**We recommend avoiding using enums as far as possible**.\n\nEnums have a few [documented issues](https://fettblog.eu/tidy-typescript-avoid-enums/) (the TS team [agrees](https://twitter.com/orta/status/1348966323271987201?s=20)). A simpler alternative to enums is just declaring a union type of string literals:\n\n```tsx\nexport declare type Position = \"left\" | \"right\" | \"top\" | \"bottom\";\n```\n\nIf you must use enums, remember that enums in TypeScript default to numbers. You will usually want to use them as strings instead:\n\n```tsx\nexport enum ButtonSizes {\n  default = \"default\",\n  small = \"small\",\n  large = \"large\",\n}\n\n// usage\nexport const PrimaryButton = (\n  props: Props & React.HTMLProps<HTMLButtonElement>\n) => <Button size={ButtonSizes.default} {...props} />;\n```\n\n#### Type Assertion\n\nSometimes you know better than TypeScript that the type you're using is narrower than it thinks, or union types need to be asserted to a more specific type to work with other APIs, so assert with the `as` keyword. This tells the compiler you know better than it does.\n\n```tsx\nclass MyComponent extends React.Component<{\n  message: string;\n}> {\n  render() {\n    const { message } = this.props;\n    return (\n      <Component2 message={message as SpecialMessageType}>{message}</Component2>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgGU61gUAbAWSQGduUBzJABVa9ALwFuMKMAB2-fAG4KFOTCRRM6egAUcYbnADeFOHBA8+ggFxwpM+XAA+cAK6yAJkkxykH5eQAvirkaBCyUnAAwriQskiyMABMtsjoMAB0AGJRADx6EAYAfHASABRG5pYCSIEAlKUlZaZwuR7AAG5FLWa5ABYAjEVGFrw1gbkA9IPd5L2T7V0UdSFobCi8cBzUMeDhCfBIAB7qnoZpGBm7cQe5JnNVYzZ20nL8AYEl92ZEnhplDW+ZjgYQi8Eqoys9ECpTgMD6wG4GTA+m4AWBcCIMFcUFkcGaDwxuWu+0SSUeULEI2qgjgG0YzFYnBpwlEn2pT1qUxJ8TJswxdXRcGCQSAA)\n\nNote that you cannot assert your way to anything - basically it is only for refining types. Therefore it is not the same as \"casting\" a type.\n\nYou can also assert a property is non-null, when accessing it:\n\n```ts\nelement.parentNode!.removeChild(element); // ! before the period\nmyFunction(document.getElementById(dialog.id!)!); // ! after the property accessing\nlet userID!: string; // definite assignment assertion... be careful!\n```\n\nOf course, try to actually handle the null case instead of asserting :)\n\n#### Simulating Nominal Types\n\nTS' structural typing is handy, until it is inconvenient. However you can simulate nominal typing with [`type branding`](https://basarat.gitbook.io/typescript/main-1/nominaltyping):\n\n```ts\ntype OrderID = string & { readonly brand: unique symbol };\ntype UserID = string & { readonly brand: unique symbol };\ntype ID = OrderID | UserID;\n```\n\nWe can create these values with the Companion Object Pattern:\n\n```ts\nfunction OrderID(id: string) {\n  return id as OrderID;\n}\nfunction UserID(id: string) {\n  return id as UserID;\n}\n```\n\nNow TypeScript will disallow you from using the wrong ID in the wrong place:\n\n```ts\nfunction queryForUser(id: UserID) {\n  // ...\n}\nqueryForUser(OrderID(\"foobar\")); // Error, Argument of type 'OrderID' is not assignable to parameter of type 'UserID'\n```\n\nIn future you can use the `unique` keyword to brand. [See this PR](https://github.com/microsoft/TypeScript/pull/33038).\n\n#### Intersection Types\n\nAdding two types together can be handy, for example when your component is supposed to mirror the props of a native component like a `button`:\n\n```tsx\nexport interface PrimaryButtonProps {\n  label: string;\n}\nexport const PrimaryButton = (\n  props: PrimaryButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>\n) => {\n  // do custom buttony stuff\n  return <button {...props}> {props.label} </button>;\n};\n```\n\n_Playground [here](https://www.typescriptlang.org/play?ssl=4&ssc=1&pln=12&pc=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCipAD0ljmADsYkpN0k4AFKUFKAE8AQgFcYMCE14QwAZzgBvCnDgAbFACMkagFxw5MPkwDmAbgoBfanWjw0Uwzz4gBI8ZKZwAvHAAUKnBgOPL6vPxCYhJSMvJwAGSIxDAAdFGeABIAKgCyADIAghJ8muJIcgA82fnpUgCiakggSCwAfBQAlD6tSoEA9H1wACYQcGiihrhwpdFMggYwopiYgUSLUF4VM55KKXvBsnKWPYoH8ika2mqWcBV921KtFuSWQA)_\n\nYou can also use Intersection Types to make reusable subsets of props for similar components:\n\n```tsx\ntype BaseProps = {\n   className?: string,\n   style?: React.CSSProperties\n   name: string // used in both\n}\ntype DogProps = {\n  tailsCount: number\n}\ntype HumanProps = {\n  handsCount: number\n}\nexport const Human = (props: BaseProps & HumanProps) => // ...\nexport const Dog = (props: BaseProps & DogProps) => // ...\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgCEUBnJABRzGbgF44BvCnGFoANi2YA5FCCQB+AFxxmMKMAB2AcwA0Q4Suqj5S5OhgA6AMIBlaxwh1YwJMz1x1MpEpVqtcAPT+cACurAAmcBpwAEYQMAAWFAC+VLT0ACIQmvZcvAJ6MCjAosyWEMHqMErqwSDRSFDJqXRwABK1KOo53HyC5MLxnWGl5ZXVtfWN5CnkSAAekLBwaBDqKm0d6ibEFgBilgA8TKzdcABkGyCd3QB8eQAUAJS8d-d6B2HAAG4BNxSPFAo80W8BWa3gmU02zM5n2RxY7E43AukNuD2ePFe70+P38f3IjyAA)\n\nMake sure not to confuse Intersection Types (which are **and** operations) with Union Types (which are **or** operations).\n\n#### Union Types\n\nThis section is yet to be written (please contribute!). Meanwhile, see our [commentary on Union Types usecases](https://github.com/typescript-cheatsheets/react/blob/main/README.md#union-types-and-type-guarding).\n\nThe ADVANCED cheatsheet also has information on Discriminated Union Types, which are helpful when TypeScript doesn't seem to be narrowing your union type as you expect.\n\n#### Overloading Function Types\n\nSpecifically when it comes to functions, you may need to overload instead of union type. The most common way function types are written uses the shorthand:\n\n```ts\ntype FunctionType1 = (x: string, y: number) => number;\n```\n\nBut this doesn't let you do any overloading. If you have the implementation, you can put them after each other with the function keyword:\n\n```ts\nfunction pickCard(x: { suit: string; card: number }[]): number;\nfunction pickCard(x: number): { suit: string; card: number };\nfunction pickCard(x): any {\n  // implementation with combined signature\n  // ...\n}\n```\n\nHowever, if you don't have an implementation and are just writing a `.d.ts` definition file, this won't help you either. In this case you can forego any shorthand and write them the old-school way. The key thing to remember here is as far as TypeScript is concerned, `functions are just callable objects with no key`:\n\n```ts\ntype pickCard = {\n  (x: { suit: string; card: number }[]): number;\n  (x: number): { suit: string; card: number };\n  // no need for combined signature in this form\n  // you can also type static properties of functions here eg `pickCard.wasCalled`\n};\n```\n\nNote that when you implement the actual overloaded function, the implementation will need to declare the combined call signature that you'll be handling, it won't be inferred for you. You can readily see examples of overloads in DOM APIs, e.g. `createElement`.\n\n[Read more about Overloading in the Handbook.](https://www.typescriptlang.org/docs/handbook/functions.html#overloads)\n\n#### Using Inferred Types\n\nLeaning on TypeScript's Type Inference is great... until you realize you need a type that was inferred, and have to go back and explicitly declare types/interfaces so you can export them for reuse.\n\nFortunately, with `typeof`, you won't have to do that. Just use it on any value:\n\n```tsx\nconst [state, setState] = useState({\n  foo: 1,\n  bar: 2,\n}); // state's type inferred to be {foo: number, bar: number}\n\nconst someMethod = (obj: typeof state) => {\n  // grabbing the type of state even though it was inferred\n  // some code using obj\n  setState(obj); // this works\n};\n```\n\n#### Using Partial Types\n\nWorking with slicing state and props is common in React. Again, you don't really have to go and explicitly redefine your types if you use the `Partial` generic type:\n\n```tsx\nconst [state, setState] = useState({\n  foo: 1,\n  bar: 2,\n}); // state's type inferred to be {foo: number, bar: number}\n\n// NOTE: stale state merging is not actually encouraged in useState\n// we are just demonstrating how to use Partial here\nconst partialStateUpdate = (obj: Partial<typeof state>) =>\n  setState({ ...state, ...obj });\n\n// later on...\npartialStateUpdate({ foo: 2 }); // this works\n```\n\n<details>\n<summary><b>Minor caveats on using <code>Partial</code></b></summary>\n\nNote that there are some TS users who don't agree with using `Partial` as it behaves today. See [subtle pitfalls of the above example here](https://twitter.com/ferdaber/status/1084798596027957248), and check out this long discussion on [why @types/react uses Pick instead of Partial](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365).\n\n</details>\n\n#### The Types I need weren't exported!\n\nThis can be annoying but here are ways to grab the types!\n\n- Grabbing the Prop types of a component: Use `React.ComponentProps` and `typeof`, and optionally `Omit` any overlapping types\n\n```tsx\nimport { Button } from \"library\"; // but doesn't export ButtonProps! oh no!\ntype ButtonProps = React.ComponentProps<typeof Button>; // no problem! grab your own!\ntype AlertButtonProps = Omit<ButtonProps, \"onClick\">; // modify\nconst AlertButton = (props: AlertButtonProps) => (\n  <Button onClick={() => alert(\"hello\")} {...props} />\n);\n```\n\nYou may also use [`ComponentPropsWithoutRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L774) (instead of ComponentProps) and [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770) (if your component specifically forwards refs)\n\n- Grabbing the return type of a function: use `ReturnType`:\n\n```tsx\n// inside some library - return type { baz: number } is inferred but not exported\nfunction foo(bar: string) {\n  return { baz: 1 };\n}\n\n//  inside your app, if you need { baz: number }\ntype FooReturn = ReturnType<typeof foo>; // { baz: number }\n```\n\nIn fact you can grab virtually anything public: [see this blogpost from Ivan Koshelev](http://ikoshelev.azurewebsites.net/search/id/11/Pragmatic-uses-of-TypeScript-type-system-My-type-of-type)\n\n```ts\nfunction foo() {\n  return {\n    a: 1,\n    b: 2,\n    subInstArr: [\n      {\n        c: 3,\n        d: 4,\n      },\n    ],\n  };\n}\n\ntype InstType = ReturnType<typeof foo>;\ntype SubInstArr = InstType[\"subInstArr\"];\ntype SubInstType = SubInstArr[0];\n\nlet baz: SubInstType = {\n  c: 5,\n  d: 6, // type checks ok!\n};\n\n//You could just write a one-liner,\n//But please make sure it is forward-readable\n//(you can understand it from reading once left-to-right with no jumps)\ntype SubInstType2 = ReturnType<typeof foo>[\"subInstArr\"][0];\nlet baz2: SubInstType2 = {\n  c: 5,\n  d: 6, // type checks ok!\n};\n```\n\n- TS also ships with a `Parameters` utility type for extracting the parameters of a function\n- for anything more \"custom\", the `infer` keyword is the basic building block for this, but takes a bit of getting used to. Look at the source code for the above utility types, and [this example](https://twitter.com/mgechev/status/1211030455224422401?s=20) to get the idea. Basarat [also has a good video on `infer`](https://www.youtube.com/watch?v=ijK-1R-LFII&list=PLYvdvJlnTOjF6aJsWWAt7kZRJvzw-en8B&index=3&t=0s).\n\n#### The Types I need don't exist!\n\nWhat's more annoying than modules with unexported types? Modules that are **untyped**!\n\n> Before you proceed - make sure you have checked that types don't exist in [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) or [TypeSearch](https://microsoft.github.io/TypeSearch/)\n\nFret not! There are more than a couple of ways in which you can solve this problem.\n\n##### Slapping `any` on everything\n\nA **lazier** way would be to create a new type declaration file, say `typedec.d.ts`– if you don't already have one. Ensure that the path to file is resolvable by TypeScript by checking the `include` array in the `tsconfig.json` file at the root of your directory.\n\n```json\n// inside tsconfig.json\n{\n  // ...\n  \"include\": [\n    \"src\" // automatically resolves if the path to declaration is src/typedec.d.ts\n  ]\n  // ...\n}\n```\n\nWithin this file, add the `declare` syntax for your desired module, say `my-untyped-module`– to the declaration file:\n\n```ts\n// inside typedec.d.ts\ndeclare module \"my-untyped-module\";\n```\n\nThis one-liner alone is enough if you just need it to work without errors. A even hackier, write-once-and-forget way would be to use `\"*\"` instead which would then apply the `Any` type for all existing and future untyped modules.\n\nThis solution works well as a workaround if you have less than a couple untyped modules. Anything more, you now have a ticking type-bomb in your hands. The only way of circumventing this problem would be to define the missing types for those untyped modules as explained in the following sections.\n\n##### Autogenerate types\n\nYou can use TypeScript with `--allowJs` and `--declaration` to see TypeScript's \"best guess\" at the types of the library.\n\nIf this doesn't work well enough, use [`dts-gen`](https://github.com/Microsoft/dts-gen) to use the runtime shape of the object to accurately enumerate all available properties. This tends to be very accurate, BUT the tool does not yet support scraping JSDoc comments to populate additional types.\n\n```bash\nnpm install -g dts-gen\ndts-gen -m <your-module>\n```\n\nThere are other automated JS to TS conversion tools and migration strategies - see [our MIGRATION cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/migration/from_js).\n\n##### Typing Exported Hooks\n\nTyping Hooks is just like typing pure functions.\n\nThe following steps work under two assumptions:\n\n- You have already created a type declaration file as stated earlier in the section.\n- You have access to the source code - specifically the code that directly exports the functions you will be using. In most cases, it would be housed in an `index.js` file.\n  Typically you need a minimum of **two** type declarations (one for **Input Prop** and the other for **Return Prop**) to define a hook completely. Suppose the hook you wish to type follows the following structure,\n\n```js\n// ...\nconst useUntypedHook = (prop) => {\n  // some processing happens here\n  return {\n    /* ReturnProps */\n  };\n};\nexport default useUntypedHook;\n```\n\nthen, your type declaration should most likely follow the following syntax.\n\n```ts\ndeclare module 'use-untyped-hook' {\n  export interface InputProps { ... }   // type declaration for prop\n  export interface ReturnProps { ... } // type declaration for return props\n  export default function useUntypedHook(\n    prop: InputProps\n    // ...\n  ): ReturnProps;\n}\n```\n\n<details>\n<summary><b>For instance, the <a href=\"https://github.com/donavon/use-dark-mode\">useDarkMode hook</a> exports the functions that follows a similar structure.</b></summary>\n\n```js\n// inside src/index.js\nconst useDarkMode = (\n  initialValue = false, // -> input props / config props to be exported\n  {\n    // -> input props / config props to be exported\n    element,\n    classNameDark,\n    classNameLight,\n    onChange,\n    storageKey = \"darkMode\",\n    storageProvider,\n    global,\n  } = {}\n) => {\n  // ...\n  return {\n    // -> return props to be exported\n    value: state,\n    enable: useCallback(() => setState(true), [setState]),\n    disable: useCallback(() => setState(false), [setState]),\n    toggle: useCallback(() => setState((current) => !current), [setState]),\n  };\n};\nexport default useDarkMode;\n```\n\nAs the comments suggest, exporting these config props and return props following the aforementioned structure will result in the following type export.\n\n```ts\ndeclare module \"use-dark-mode\" {\n  /**\n   * A config object allowing you to specify certain aspects of `useDarkMode`\n   */\n  export interface DarkModeConfig {\n    classNameDark?: string; // A className to set \"dark mode\". Default = \"dark-mode\".\n    classNameLight?: string; // A className to set \"light mode\". Default = \"light-mode\".\n    element?: HTMLElement; // The element to apply the className. Default = `document.body`\n    onChange?: (val?: boolean) => void; // Override the default className handler with a custom callback.\n    storageKey?: string; // Specify the `localStorage` key. Default = \"darkMode\". Set to `null` to disable persistent storage.\n    storageProvider?: WindowLocalStorage; // A storage provider. Default = `localStorage`.\n    global?: Window; // The global object. Default = `window`.\n  }\n  /**\n   * An object returned from a call to `useDarkMode`.\n   */\n  export interface DarkMode {\n    readonly value: boolean;\n    enable: () => void;\n    disable: () => void;\n    toggle: () => void;\n  }\n  /**\n   * A custom React Hook to help you implement a \"dark mode\" component for your application.\n   */\n  export default function useDarkMode(\n    initialState?: boolean,\n    config?: DarkModeConfig\n  ): DarkMode;\n}\n```\n\n</details>\n\n##### Typing Exported Components\n\nIn case of typing untyped class components, there's almost no difference in approach except for the fact that after declaring the types, you export the extend the type using `class UntypedClassComponent extends React.Component<UntypedClassComponentProps, any> {}` where `UntypedClassComponentProps` holds the type declaration.\n\nFor instance, [sw-yx's Gist on React Router 6 types](https://gist.github.com/sw-yx/37a6a3d248c2d4031801f0d568904df8) implemented a similar method for typing the then untyped RR6.\n\n```ts\ndeclare module \"react-router-dom\" {\n  import * as React from 'react';\n  // ...\n  type NavigateProps<T> = {\n    to: string | number,\n    replace?: boolean,\n    state?: T\n  }\n  //...\n  export class Navigate<T = any> extends React.Component<NavigateProps<T>>{}\n  // ...\n```\n\nFor more information on creating type definitions for class components, you can refer to this [post](https://templecoding.com/blog/2016/03/31/creating-typescript-typings-for-existing-react-components) for reference.\n\n#### Frequent Known Problems with TypeScript\n\nJust a list of stuff that React developers frequently run into, that TS has no solution for. Not necessarily TSX only.\n\n##### TypeScript doesn't narrow after an object element null check\n\n[![https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg&name=medium](https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg&name=medium)](https://mobile.twitter.com/tannerlinsley/status/1390409931627499523)\n\nRef: https://mobile.twitter.com/tannerlinsley/status/1390409931627499523. see also https://github.com/microsoft/TypeScript/issues/9998\n\n##### TypeScript doesn't let you restrict the type of children\n\nGuaranteeing typesafety for this kind of API isn't possible:\n\n```tsx\n<Menu>\n  <MenuItem/> {/* ok */}\n  <MenuLink/> {/* ok */}\n  <div> {/* error */}\n</Menu>\n```\n\nSource: https://twitter.com/ryanflorence/status/1085745787982700544?s=20\n\n<!--END-SECTION:types-->\n\n<!--START-SECTION:operators-->\n\n### Troubleshooting Handbook: Operators\n\n- `typeof` and `instanceof`: type query used for refinement\n- `keyof`: get keys of an object. `keyof T` is an operator to tell you what values of `k` can be used for `obj[k]`.\n  - [Some misconceptions here](https://twitter.com/SeaRyanC/status/1418678670739218438?s=20).\n- `O[K]`: property lookup\n- `[K in O]`: mapped types\n- `+` or `-` or `readonly` or `?`: addition and subtraction and readonly and optional modifiers\n- `x ? Y : Z`: Conditional types for generic types, type aliases, function parameter types\n- `!`: Nonnull assertion for nullable types\n- `=`: Generic type parameter default for generic types\n- `as`: type assertion\n- `is`: type guard for function return types\n\nConditional Types are a difficult topic to get around so here are some extra resources:\n\n- fully walked through explanation https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/\n- Bailing out and other advanced topics https://github.com/sw-yx/ts-spec/blob/master/conditional-types.md\n- Basarat's video https://www.youtube.com/watch?v=SbVgPQDealg&list=PLYvdvJlnTOjF6aJsWWAt7kZRJvzw-en8B&index=2&t=0s\n- [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ&feature=youtu.be)\n\n<!--END-SECTION:operators-->\n\n<!--START-SECTION:utilities-->\n\n### Troubleshooting Handbook: Utilities\n\nThese are all built in, [see source in es5.d.ts](https://github.com/microsoft/TypeScript/blob/33a34e5b96bfe086266f4765ab9789a2a02507f9/src/lib/es5.d.ts#L1523-L1637):\n\n- `Awaited`: emulate the behavior of `await`\n- `Capitalize`: convert first character of string literal type to uppercase\n- `ConstructorParameters`: a tuple of class constructor's parameter types\n- `Exclude`: exclude a type from another type\n- `Extract`: select a subtype that is assignable to another type\n- `InstanceType`: the instance type you get from a `new`ing a class constructor\n- `Lowercase`: convert string literal type to lowercase\n- `NonNullable`: exclude `null` and `undefined` from a type\n- `Omit`: construct a type with the properties of another type.\n- `OmitThisParameter`: remove the 'this' parameter from a function type.\n- `Parameters`: a tuple of a function's parameter types\n- `Partial`: Make all properties in an object optional\n- `Readonly`: Make all properties in an object readonly\n- `ReadonlyArray`: Make an immutable array of the given type\n- `Pick`: A subtype of an object type with a subset of its keys\n- `Record`: A map from a key type to a value type\n- `Required`: Make all properties in an object required\n- `ReturnType`: A function's return type\n- `ThisParameterType`: extract the type of the 'this' parameter of a function type\n- `ThisType`: marker for contextual 'this' type\n- `Uncapitalize`: convert first character of string literal type to lowercase\n- `Uppercase`: convert string literal type to uppercase\n\n<!--END-SECTION:utilities-->\n\n<!--START-SECTION:ts-config-->\n\n### Troubleshooting Handbook: tsconfig.json\n\nYou can find [all the Compiler options in the TypeScript docs](https://www.typescriptlang.org/docs/handbook/compiler-options.html). [The new TS docs also has per-flag annotations of what each does](https://www.typescriptlang.org/tsconfig#allowSyntheticDefaultImports). This is the setup I roll with for APPS (not libraries - for libraries you may wish to see the settings we use in `tsdx`):\n\n```json\n{\n  \"compilerOptions\": {\n    \"incremental\": true,\n    \"outDir\": \"build/lib\",\n    \"target\": \"es5\",\n    \"module\": \"esnext\",\n    \"lib\": [\"DOM\", \"ESNext\"],\n    \"sourceMap\": true,\n    \"importHelpers\": true,\n    \"declaration\": true,\n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noImplicitReturns\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"allowJs\": false,\n    \"jsx\": \"react\",\n    \"moduleResolution\": \"node\",\n    \"baseUrl\": \"src\",\n    \"forceConsistentCasingInFileNames\": true,\n    \"esModuleInterop\": true,\n    \"suppressImplicitAnyIndexErrors\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"experimentalDecorators\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"build\", \"scripts\"]\n}\n```\n\nYou can find more [recommended TS config here](https://github.com/tsconfig/bases).\n\nPlease open an issue and discuss if there are better recommended choices for React.\n\nSelected flags and why we like them:\n\n- `esModuleInterop`: disables namespace imports (`import * as foo from \"foo\"`) and enables CJS/AMD/UMD style imports (`import fs from \"fs\"`)\n- `strict`: `strictPropertyInitialization` forces you to initialize class properties or explicitly declare that they can be undefined. You can opt out of this with a definite assignment assertion.\n- `\"typeRoots\": [\"./typings\", \"./node_modules/@types\"]`: By default, TypeScript looks in `node_modules/@types` and parent folders for third party type declarations. You may wish to override this default resolution so you can put all your global type declarations in a special `typings` folder.\n\nCompilation time grows linearly with size of codebase. For large projects, you will want to use [Project References](https://www.typescriptlang.org/docs/handbook/project-references.html). See our [ADVANCED](https://react-typescript-cheatsheet.netlify.app/docs/advanced) cheatsheet for commentary.\n\n<!--END-SECTION:ts-config-->\n\n<!--START-SECTION:official-typings-bugs-->\n\n### Troubleshooting Handbook: Fixing bugs in official typings\n\nIf you run into bugs with your library's official typings, you can copy them locally and tell TypeScript to use your local version using the \"paths\" field. In your `tsconfig.json`:\n\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"mobx-react\": [\"../typings/modules/mobx-react\"]\n    }\n  }\n}\n```\n\n[Thanks to @adamrackis for the tip.](https://twitter.com/AdamRackis/status/1024827730452520963)\n\nIf you just need to add an interface, or add missing members to an existing interface, you don't need to copy the whole typing package. Instead, you can use [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html):\n\n```tsx\n// my-typings.ts\ndeclare module \"plotly.js\" {\n  interface PlotlyHTMLElement {\n    removeAllListeners(): void;\n  }\n}\n\n// MyComponent.tsx\nimport { PlotlyHTMLElement } from \"plotly.js\";\n\nconst f = (e: PlotlyHTMLElement) => {\n  e.removeAllListeners();\n};\n```\n\nYou don't always have to implement the module, you can simply import the module as `any` for a quick start:\n\n```tsx\n// my-typings.ts\ndeclare module \"plotly.js\"; // each of its imports are `any`\n```\n\nBecause you don't have to explicitly import this, this is known as an [ambient module declaration](https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html#pitfalls-of-namespaces-and-modules). You can do AMD's in a script-mode `.ts` file (no imports or exports), or a `.d.ts` file anywhere in your project.\n\nYou can also do ambient variable and ambient type declarations:\n\n```ts\n// ambient utility type\ntype ToArray<T> = T extends unknown[] ? T : T[];\n// ambient variable\ndeclare let process: {\n  env: {\n    NODE_ENV: \"development\" | \"production\";\n  };\n};\nprocess = {\n  env: {\n    NODE_ENV: \"production\",\n  },\n};\n```\n\nYou can see examples of these included in the built in type declarations in the `lib` field of `tsconfig.json`\n\n<!--END-SECTION:official-typings-bugs-->\n\n<!--START-SECTION:non-ts-files-->\n\n### Troubleshooting Handbook: Globals, Images and other non-TS files\n\nUse [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).\n\nIf, say, you are using a third party JS script that attaches on to the `window` global, you can extend `Window`:\n\n```ts\ndeclare global {\n  interface Window {\n    MyVendorThing: MyVendorType;\n  }\n}\n```\n\nLikewise if you wish to \"import\" an image or other non TS/TSX file:\n\n```ts\n// declaration.d.ts\n// anywhere in your project, NOT the same name as any of your .ts/tsx files\ndeclare module \"*.png\";\n\n// importing in a tsx file\nimport * as logo from \"./logo.png\";\n```\n\nNote that `tsc` cannot bundle these files for you, you will have to use Webpack or Parcel.\n\nRelated issue: https://github.com/Microsoft/TypeScript-React-Starter/issues/12 and [StackOverflow](https://stackoverflow.com/a/49715468/4216035)\n\n<!--END-SECTION:non-ts-files-->\n\n<!--START-SECTION:editor-integration-->\n\n### Editor Tooling and Integration\n\n- VSCode\n  - swyx's VSCode Extension: https://github.com/sw-yx/swyx-react-typescript-snippets\n  - amVim: https://marketplace.visualstudio.com/items?itemName=auiworks.amvim\n- VIM\n  - https://github.com/Quramy/tsuquyomi\n  - nvim-typescript?\n  - https://github.com/leafgarland/typescript-vim\n  - peitalin/vim-jsx-typescript\n  - NeoVim: https://github.com/neoclide/coc.nvim\n  - other discussion: https://mobile.twitter.com/ryanflorence/status/1085715595994095620\n\nYou are free to use this repo's TSX logo if you wish:\n\n[![https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png](https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png)](https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png)\n\nYou may also wish to use alternative logos - [jsx-tsx-logos](https://github.com/Protectator/jsx-tsx-logos)\n\n![https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png](https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png)\n\n<!--END-SECTION:editor-integration-->\n\n<!--START-SECTION:linting-->\n\n### Linting\n\n> ⚠️Note that [TSLint is now in maintenance and you should try to use ESLint instead](https://medium.com/palantir/tslint-in-2019-1a144c2317a9). If you are interested in TSLint tips, please check this PR from [@azdanov](https://github.com/typescript-cheatsheets/react/pull/14). The rest of this section just focuses on ESLint. [You can convert TSlint to ESlint with this tool](https://github.com/typescript-eslint/tslint-to-eslint-config).\n\n> ⚠️This is an evolving topic. `typescript-eslint-parser` is no longer maintained and [work has recently begun on `typescript-eslint` in the ESLint community](https://eslint.org/blog/2019/01/future-typescript-eslint) to bring ESLint up to full parity and interop with TSLint.\n\nFollow the TypeScript + ESLint docs at https://github.com/typescript-eslint/typescript-eslint:\n\n```\nyarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint\n```\n\nadd a `lint` script to your `package.json`:\n\n```json\n  \"scripts\": {\n    \"lint\": \"eslint 'src/**/*.ts'\"\n  },\n```\n\nand a suitable `.eslintrc.js` (using `.js` over `.json` here so we can add comments):\n\n```js\nmodule.exports = {\n  env: {\n    es6: true,\n    node: true,\n    jest: true,\n  },\n  extends: \"eslint:recommended\",\n  parser: \"@typescript-eslint/parser\",\n  plugins: [\"@typescript-eslint\"],\n  parserOptions: {\n    ecmaVersion: 2017,\n    sourceType: \"module\",\n  },\n  rules: {\n    indent: [\"error\", 2],\n    \"linebreak-style\": [\"error\", \"unix\"],\n    quotes: [\"error\", \"single\"],\n    \"no-console\": \"warn\",\n    \"no-unused-vars\": \"off\",\n    \"@typescript-eslint/no-unused-vars\": [\n      \"error\",\n      { vars: \"all\", args: \"after-used\", ignoreRestSiblings: false },\n    ],\n    \"@typescript-eslint/explicit-function-return-type\": \"warn\", // Consider using explicit annotations for object literals and function return types even when they can be inferred.\n    \"no-empty\": \"warn\",\n  },\n};\n```\n\nMost of this is taken from [the `tsdx` PR](https://github.com/palmerhq/tsdx/pull/70/files) which is for **libraries**.\n\nMore `.eslintrc.json` options to consider with more options you may want for **apps**:\n\n```json\n{\n  \"extends\": [\n    \"airbnb\",\n    \"prettier\",\n    \"prettier/react\",\n    \"plugin:prettier/recommended\",\n    \"plugin:jest/recommended\",\n    \"plugin:unicorn/recommended\"\n  ],\n  \"plugins\": [\"prettier\", \"jest\", \"unicorn\"],\n  \"parserOptions\": {\n    \"sourceType\": \"module\",\n    \"ecmaFeatures\": {\n      \"jsx\": true\n    }\n  },\n  \"env\": {\n    \"es6\": true,\n    \"browser\": true,\n    \"jest\": true\n  },\n  \"settings\": {\n    \"import/resolver\": {\n      \"node\": {\n        \"extensions\": [\".js\", \".jsx\", \".ts\", \".tsx\"]\n      }\n    }\n  },\n  \"overrides\": [\n    {\n      \"files\": [\"**/*.ts\", \"**/*.tsx\"],\n      \"parser\": \"typescript-eslint-parser\",\n      \"rules\": {\n        \"no-undef\": \"off\"\n      }\n    }\n  ]\n}\n```\n\nAnother great resource is [\"Using ESLint and Prettier in a TypeScript Project\"](https://dev.to/robertcoopercode/using-eslint-and-prettier-in-a-typescript-project-53jb) by @robertcoopercode.\n\nWes Bos is also working on [TypeScript support for his eslint+prettier config.](https://github.com/wesbos/eslint-config-wesbos/issues/68)\n\nIf you're looking for information on Prettier, check out the [Prettier](https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/misc-concerns.md#prettier) guide.\n\n<!--END-SECTION:linting-->\n\n<!--START-SECTION:resources-->\n\n### Other React + TypeScript resources\n\n- me! <https://twitter.com/swyx>\n- https://www.freecodecamp.org/news/how-to-build-a-todo-app-with-react-typescript-nodejs-and-mongodb/\n- <https://github.com/piotrwitek/react-redux-typescript-guide> - **HIGHLY HIGHLY RECOMMENDED**, i wrote this repo before knowing about this one, this has a lot of stuff I don't cover, including **REDUX** and **JEST**.\n- [10 Bad TypeScript Habits](https://startup-cto.net/10-bad-typescript-habits-to-break-this-year/):\n  1. not using `\"strict\": true`\n  2. using `||` for default values when we have `??`\n  3. Using `any` instead of `unknown` for API responses\n  4. using `as` assertion instead of Type Guards (`function isFoo(obj: unknown): obj is Foo {}`)\n  5. `as any` in tests\n  6. Marking optional properties instead of modeling which combinations exist by extending interfaces\n  7. One letter generics\n  8. Non-boolean `if (nonboolean)` checks\n  9. bangbang checks `if (!!nonboolean)`\n  10. `!= null` to check for `null` and `undefined`\n- [Ultimate React Component Patterns with TypeScript 2.8](https://levelup.gitconnected.com/ultimate-react-component-patterns-with-typescript-2-8-82990c516935)\n- [Basarat's TypeScript gitbook has a React section](https://basarat.gitbook.io/typescript/tsx/react) with an [Egghead.io course](https://egghead.io/courses/use-typescript-to-develop-react-applications) as well.\n- [Palmer Group's TypeScript + React Guidelines](https://github.com/palmerhq/typescript) as well as Jared's other work like [disco.chat](https://github.com/jaredpalmer/disco.chat)\n- [Sindre Sorhus' TypeScript Style Guide](https://github.com/sindresorhus/typescript-definition-style-guide)\n- [TypeScript React Starter Template by Microsoft](https://github.com/Microsoft/TypeScript-React-Starter) A starter template for TypeScript and React with a detailed README describing how to use the two together. Note: this doesn't seem to be frequently updated anymore.\n- [Steve Kinney's React and TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/react-typescript/)\n- [Brian Holt's Intermediate React course on Frontend Masters (paid)](https://frontendmasters.com/courses/intermediate-react/converting-the-app-to-typescript/) - Converting App To TypeScript Section\n- [Mike North's Production TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/production-typescript/)\n- [TSX Guide](https://jenil.github.io/chota/) by [gojutin](https://github.com/gojutin/www.tsx.guide)\n- TypeScript conversion:\n  - [Lyft's React-To-TypeScript conversion CLI](https://github.com/lyft/react-javascript-to-typescript-transform)\n  - [Gustav Wengel's blogpost - converting a React codebase to TypeScript](http://www.gustavwengel.dk/converting-typescript-to-javascript-part-1)\n  - [Microsoft React TypeScript conversion guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide)\n- [Matt Pocock's Beginner's Typescript Tutorial](https://github.com/total-typescript/beginners-typescript-tutorial)\n- [Matt Pocock's React with TypeScript Tutorial](https://www.totaltypescript.com/tutorials/react-with-typescript)\n- [You?](https://github.com/typescript-cheatsheets/react/issues/new).\n\n<!--END-SECTION:resources-->\n\n<!--START-SECTION:talks-->\n\n### Recommended React + TypeScript talks\n\n- [Ultimate React Component Patterns with TypeScript](https://www.youtube.com/watch?v=_PBQ3if6Fmg), by Martin Hochel, GeeCon Prague 2018\n- [How to Build React Apps with TypeScript](https://youtu.be/LJzGGmu5APA?si=YNzy7T_8yj7TuXxS), by ClearEdge Tech Talk 2022\n- [Create a More Readable React Codebase Using TypeScript](https://youtu.be/nkJbGgieALI?si=IFZZIMEiXz7AsiBv), by Emma Brillhart 2019\n- [Advanced TypeScript with React](https://youtu.be/zQfD4ZxxyKA?si=FmrgOq667svX6C9O), by Nikhil Verma 2019\n- [Senior Typescript Features You don't Know About - clean-code](https://www.youtube.com/watch?v=Y4u97vJqmhM), by CoderOne 2023\n- [React & TypeScript - Course for Beginners](https://www.youtube.com/watch?v=FJDVKeh7RJI), by FreeCodeCamp 2022\n- [TypeScript + React](https://www.youtube.com/watch?v=1ZnrX3wiNTU), by Chris Toomey 2019\n- [Mastering React Hooks](https://www.youtube.com/watch?v=zM_ZiSl2n2E), by Jack Herrington 2021\n- [Using Hooks and codegen](https://www.youtube.com/watch?v=cdsnzfJUqm0) by Tejas Kumar 2019\n\n- Please help contribute to this new section!\n\n<!--END-SECTION:talks-->\n\n<!--START-SECTION:learn-ts-->\n\n### Time to Really Learn TypeScript\n\nBelieve it or not, we have only barely introduced TypeScript here in this cheatsheet. If you are still facing TypeScript troubleshooting issues, it is likely that your understanding of TS is still too superficial.\n\nThere is a whole world of generic type logic that you will eventually get into, however it becomes far less dealing with React than just getting good at TypeScript so it is out of scope here. But at least you can get productive in React now :)\n\nIt is worth mentioning some resources to help you get started:\n\n- Step through the 40+ examples under [the playground's](http://www.typescriptlang.org/play/index.html) Examples section, written by @Orta\n- Anders Hejlsberg's overview of TS: https://www.youtube.com/watch?v=ET4kT88JRXs\n- Marius Schultz: https://blog.mariusschulz.com/series/typescript-evolution with an [Egghead.io course](https://egghead.io/courses/advanced-static-types-in-typescript)\n- Basarat's Deep Dive: https://basarat.gitbook.io/typescript/\n- Axel Rauschmeyer's [Tackling TypeScript](https://exploringjs.com/tackling-ts/)\n- Rares Matei: [Egghead.io course](https://egghead.io/courses/practical-advanced-typescript)'s advanced TypeScript course on Egghead.io is great for newer typescript features and practical type logic applications (e.g. recursively making all properties of a type `readonly`)\n- Learn about [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ&feature=youtu.be)\n- Shu Uesugi: [TypeScript for Beginner Programmers](https://ts.chibicode.com/)\n- Here is another [TypeScript Error Guide](https://github.com/threehams/typescript-error-guide/) that you can check for your errors.\n\n<!--END-SECTION:learn-ts-->\n\n<!--START-SECTION:examples-->\n\n### Example App\n\n- [Create React App TypeScript Todo Example 2021](https://github.com/laststance/create-react-app-typescript-todo-example-2021)\n- [Ben Awad's 14 hour Fullstack React/GraphQL/TypeScript Tutorial](https://www.youtube.com/watch?v=I6ypD7qv3Z8)\n- [Cypress Realworld App](https://github.com/cypress-io/cypress-realworld-app)\n\n<!--END-SECTION:examples-->\n\n## My question isn't answered here!\n\n- [File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new).\n\n## Contributors\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. See [CONTRIBUTORS.md](/CONTRIBUTORS.md) for the full list. Contributions of any kind welcome!\n"
  },
  {
    "path": "code-of-conduct.md",
    "content": "# Our Code of Conduct\n\nThis code of conduct outlines our expectations for participants within\nthe [typescript-cheatsheets/react](https://github.com/typescript-cheatsheets/react) repository, as well as steps to\nreporting unacceptable behavior. We are committed to providing a welcoming and inspiring community for all and expect\nour code of conduct to be honored. Anyone who violates this code of conduct may be banned from the community.\n\nOur open source repository strives to:\n\n- **Be friendly and patient.**\n- **Be welcoming**: We strive to be a community that welcomes and supports people of all backgrounds and identities.\n  This includes, but is not limited to members of any race, ethnicity, culture, national origin, colour, immigration\n  status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age,\n  size, family status, political belief, religion, and mental and physical ability.\n- **Be considerate**: Your work will be used by other people, and you in turn will depend on the work of others. Any\n  decision you take will affect users and colleagues, and you should take those consequences into account when making\n  decisions. Remember that we're a world-wide community, so you might not be communicating in someone else's primary\n  language.\n- **Be respectful**: Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor\n  manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a\n  personal attack. It’s important to remember that a community where people feel uncomfortable or threatened is not a\n  productive one.\n- **Be careful in the words that you choose**: we are a community of professionals, and we conduct ourselves\n  professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary\n  behavior aren't acceptable. This includes, but is not limited to:\n  - Violent threats or language directed against another person.\n  - Discriminatory jokes and language.\n  - Posting sexually explicit or violent material.\n  - Posting (or threatening to post) other people's personally identifying information (\"doxing\").\n  - Personal insults, especially those using racist or sexist terms.\n  - Unwelcome sexual attention.\n  - Advocating for, or encouraging, any of the above behavior.\n  - Repeated harassment of others. In general, if someone asks you to stop, then stop.\n- **When we disagree, try to understand why**: Disagreements, both social and technical, happen all the time. It is\n  important that we resolve disagreements and differing views constructively. Remember that we’re different. The\n  strength of our community comes from its diversity, people from a wide range of backgrounds. Different people have\n  different perspectives on issues. Being unable to understand why someone holds a viewpoint doesn’t mean that they’re\n  wrong. Don’t forget that it is human to err and blaming each other doesn’t get us anywhere. Instead, focus on helping\n  to resolve issues and learning from mistakes.\n\nThis code is not exhaustive or complete. It serves to distill our common understanding of a collaborative, shared\nenvironment, and goals. We expect it to be followed in spirit as much as in the letter.\n\n### Diversity Statement\n\nWe encourage everyone to participate and are committed to building a repository for all. Although we may not be able to\nsatisfy everyone, we all agree that everyone is equal. Whenever a participant has made a mistake, we expect them to take\nresponsibility for it. If someone has been harmed or offended, it is our responsibility to listen carefully and\nrespectfully, and do our best to right the wrong.\n\nAlthough this list cannot be exhaustive, we explicitly honor diversity in age, gender, gender identity or expression,\nculture, ethnicity, language, national origin, political beliefs, profession, race, religion, sexual orientation,\nsocioeconomic status, and technical ability. We will not tolerate discrimination based on any of the protected\ncharacteristics above, including participants with disabilities.\n\n### Reporting Issues\n\nIf you experience or witness unacceptable behavior—or have any other concerns—please report it by contacting us (This\nrepo is maintained by [@swyx](https://twitter.com/swyx), [@eps1lon](https://twitter.com/sebsilbermann)\nand [@filiptammergard](https://twitter.com/tammergard).). All reports will be handled with discretion. In your report\nplease include:\n\n- Your contact information.\n- Names (real, nicknames, or pseudonyms) of any individuals involved. If there are additional witnesses, please include\n  them as well. Your account of what occurred, and if you believe the incident is ongoing. If there is a publicly\n  available record (e.g. a mailing list archive or a public IRC logger), please include a link.\n- Any additional information that may be helpful.\n\nAfter filing a report, a representative will contact you personally. If the person who is harassing you is part of the\nresponse team, they will recuse themselves from handling your incident. A representative will then review the incident,\nfollow up with any additional questions, and make a decision as to how to respond. We will respect confidentiality\nrequests for the purpose of protecting victims of abuse.\n\nAnyone asked to stop unacceptable behavior is expected to comply immediately. If an individual engages in unacceptable\nbehavior, the representative may take any action they deem appropriate, up to and including a permanent ban from our\ncommunity without warning.\n\n## Version\n\nThis is version 1.0.0\n\n## Thanks\n\nThis code of conduct is based on the [Open Code of Conduct](https://github.com/todogroup/opencodeofconduct) from\nthe [TODOGroup](http://todogroup.org).\n\nWe are thankful for their work and all the communities who have paved the way with code of conducts.\n"
  },
  {
    "path": "copyFile.js",
    "content": "const fs = require(\"fs\");\nconst filesTopCopy = [\n  {\n    src: \"../CONTRIBUTORS.md\",\n    dest: \"src/pages/contributors.md\",\n  },\n  {\n    src: \"../CONTRIBUTING.md\",\n    dest: \"src/pages/contributing.md\",\n  },\n];\n\nfunction copyFile(src, dest) {\n  fs.copyFile(src, dest, (err) => {\n    if (err) {\n      console.log(\"Error Found:\", err);\n    } else {\n      console.log(\"Files copied\");\n    }\n  });\n}\n\nfilesTopCopy.forEach(({ src, dest }) => {\n  copyFile(src, dest);\n});\n"
  },
  {
    "path": "docs/advanced/index.md",
    "content": "---\nid: intro\nsidebar_label: Intro\ntitle: Advanced Cheatsheet\n---\n\n**This Advanced Cheatsheet** helps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+React **libraries**.\n\n- It also has miscellaneous tips and tricks for pro users.\n- Advice for contributing to DefinitelyTyped\n- The goal is to take _full advantage_ of TypeScript.\n\n**Creating React + TypeScript Libraries**\n\nThe best tool for creating React + TS libraries right now is [`tsdx`](https://github.com/palmerhq/tsdx). Run `npx tsdx create` and select the \"react\" option. You can view [the React User Guide](https://github.com/palmerhq/tsdx/issues/5) for a few tips on React+TS library best practices and optimizations for production.\n\nAnother option is [Rollpkg](https://github.com/rafgraph/rollpkg), which uses Rollup and the TypeScript compiler (not Babel) to create packages. It includes default configs for TypeScript, Prettier, ESLint, and Jest (setup for use with React), as well as Bundlephobia package stats for each build.\n\n- Be sure to also check [`basarat`'s guide](https://basarat.gitbooks.io/typescript/content/docs/quick/library.html) for library tsconfig settings.\n- Alec Larson: [The best Rollup config for TypeScript libraries](https://gist.github.com/aleclarson/9900ed2a9a3119d865286b218e14d226)\n- From the Angular world, check out https://github.com/bitjson/typescript-starter\n"
  },
  {
    "path": "docs/advanced/misc-concerns.md",
    "content": "---\nid: misc_concerns\ntitle: \"Section 3: Misc. Concerns\"\nsidebar_label: Misc. Concerns\n---\n\nSometimes writing React isn't just about React. While we don't focus on other libraries like Redux (see below for more on that), here are some tips on other common concerns when making apps with React + TypeScript.\n\n## Writing TypeScript Libraries instead of Apps\n\n`propTypes` may seem unnecessary with TypeScript, especially when building React + TypeScript **apps**, but they are still relevant when writing **libraries** which may be used by developers working in Javascript.\n\n```ts\ninterface MyComponentProps {\n  autoHeight: boolean;\n  secondProp: number;\n}\n\nexport class MyComponent extends React.Component<MyComponentProps, {}> {\n  static propTypes = {\n    autoHeight: PropTypes.bool,\n    secondProp: PropTypes.number.isRequired,\n  };\n}\n```\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n## Commenting Components\n\nTypeScript uses [TSDoc](https://github.com/Microsoft/tsdoc), a variant of JSDoc for TypeScript. This is very handy for writing component libraries and having useful descriptions pop up in autocomplete and other tooling (like the [Docz PropsTable](https://www.docz.site/docs/components-api#propstable)). The main thing to remember is to use `/** YOUR_COMMENT_HERE */` syntax in the line just above whatever you're annotating.\n\n```tsx\ninterface MyComponentProps {\n  /** Description of prop \"label\".\n   * @default foobar\n   * */\n  label?: string;\n}\n\n/**\n * General component description in JSDoc format. Markdown is *supported*.\n */\nexport default function MyComponent({ label = \"foobar\" }: MyComponentProps) {\n  return <div>Hello world {label}</div>;\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoC4AOxiSk3STgFkBPABRzAGc4BvCnDgB6AFRi4AESQ80UYGBjAI1OBExww3OACIANigBGSfboB0Q4ZIACAEySMArvqwQIRlFCtxJYkVaGJvoA-ABccDwwCtQA5gDcFAC+FBTiYkKSAOJI1PQo+nBouJB5tHAOcgpKKmo0cABSAMpSEGhwmNAgKDDmrF4A1nYQAO51fGI8TmCQsEh2YpbkvgHkSAAes-AOzq4dTtQYtaxsAMIlqrkwABT8cEGmcAC8ep0eXrpwSRHsXBC8AEoBFYiDAnFA1AAeOzAABuAD4ABKmfQQOAjaD6OwCB76JKQkQwhGJchJIA)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n## Namespaced Components\n\nOften when creating similar components or components that have a parent-child relationship, it is useful to namespace your components. Types can easily be added be using `Object.assign()`;\n\n```tsx\nimport { forwardRef } from \"react\";\n\nconst Input = (props: any) => <input {...props} />;\n\nconst Form = forwardRef<HTMLDivElement, any>(\n  ({ children, ...otherProps }, ref) => (\n    <form {...otherProps} ref={ref}>\n      {children}\n    </form>\n  )\n);\n\n/**\n * Exported components now can be used as `<Form>` and `<Form.Input>`\n */\nexport default Object.assign(Form, { Input: Input });\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2&ssl=1&ssc=1&pln=14&pc=52#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtCAOwGd4BJGsAV3gF44AKMHMOgC44KGgE8AlHA4A+OAB5gLdnADeAOk18IAgL5wA9DIpVaDOADFoeLsnQx1maAHcUUACbJM8gBIAVAFkAGQARYAA3AFEAGyQQJBoYABoRcRlublU0AAtgaPciGhTNdQgYbKQoAAV+Ol0UokwpWR4KOAUnKDwNTTKK6tr9Ro5VRt1jcnb2rNz8wt02hQNOkAmJCQBuE3IDACpdtt24SIAPSFgkdzhqcFoEmDo4Gghna9E4ACMkOFY6S5FHgADeRWLoyQGpK7A0EgdTMNgwcGHAwUJBnaDwdxITAoVjReAAeQ+ACskBh1Cg6HRgABzGjcGEpVTw9jCFkwXSbIA)\n\n(Contributed by @bryceosterhaus, see [further discussion](https://github.com/typescript-cheatsheets/react/issues/165))\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n## Design System Development\n\nI do like [Docz](https://docz.site/) which takes basically [1 line of config](https://www.docz.site/documentation/project-configuration#typescript) to accept TypeScript. However it is newer and has a few more rough edges (many breaking changes since it is still < v1.0)\n\nFor developing with Storybook, read the docs I wrote over here: <https://storybook.js.org/configurations/typescript-config/>. This includes automatic proptype documentation generation, which is awesome :)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n## Migrating From Flow\n\nYou should check out large projects that are migrating from flow to pick up concerns and tips:\n\n- [Jest](https://github.com/facebook/jest/pull/7554)\n- [Expo](https://github.com/expo/expo/issues/2164)\n- [React-beautiful-dnd](https://github.com/atlassian/react-beautiful-dnd/issues/982)\n- [Storybook](https://github.com/storybooks/storybook/issues/5030)\n- [VueJS](https://medium.com/the-vue-point/plans-for-the-next-iteration-of-vue-js-777ffea6fabf)\n\nUseful libraries:\n\n- <https://github.com/bcherny/flow-to-typescript>\n- <https://github.com/Khan/flow-to-ts>\n- <https://github.com/piotrwitek/utility-types>\n\nIf you have specific advice in this area, please file a PR!\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n## Prettier\n\nThere isn't any real secret to Prettier for TypeScript. But its a great idea to run prettier on every commit!\n\n```bash\n$ yarn add -D prettier husky lint-staged\n```\n\n```json\n// inside package.json\n{\n  //...\n  \"husky\": {\n    \"hooks\": {\n      \"pre-commit\": \"lint-staged\"\n    }\n  },\n  \"lint-staged\": {\n    \"linters\": {\n      \"src/*.{ts,tsx,js,jsx,css,scss,md}\": [\n        \"prettier --trailing-comma es5 --single-quote --write\",\n        \"git add\"\n      ],\n      \"ignore\": [\"**/dist/*, **/node_modules/*\"]\n    }\n  },\n  \"prettier\": {\n    \"printWidth\": 80,\n    \"semi\": false,\n    \"singleQuote\": true,\n    \"trailingComma\": \"es5\"\n  }\n}\n```\n\nIntegrating this with ESlint may be a problem. We haven't written much on this yet, please contribute if you have a strong opinion. [Here's a helpful gist.](https://gist.github.com/JirkaVebr/519c7597517e4ba756d5b89e7cb4cc0e)\n\nFor library authors, this is set up for you in [tsdx](https://github.com/palmerhq/tsdx/pull/45/files). You may also wish to check out the newer https://ts-engine.dev/ project.\n\n## Testing\n\nYes, you can test your types! You shouldn't use it for EVERYTHING, but it can help prevent regressions:\n\n- https://github.com/azz/jest-runner-tsc\n- https://github.com/SamVerschueren/tsd\n- https://github.com/ikatyang/dts-jest ([Demo](https://codesandbox.io/s/dts-test-frozen-public-demo-iyorn))\n- https://github.com/microsoft/dtslint ([Intro to dtslint](https://www.youtube.com/watch?v=nygcFEwOG8w&feature=share))\n\n## Working with Non-TypeScript Libraries (writing your own index.d.ts)\n\nLets say you want to use `de-indent`, but it isn't typed or on DefinitelyTyped. You get an error like this:\n\n```\n[ts]\nCould not find a declaration file for module 'de-indent'. '/Users/swyx/Work/react-sfc-loader/node_modules/de-indent/index.js' implicitly has an 'any' type.\n  Try `npm install @types/de-indent` if it exists or add a new declaration (.d.ts) file containing `declare module 'de-indent';` [7016]\n```\n\nSo create a `.d.ts` file anywhere in your project with the module definition:\n\n```ts\n// de-indent.d.ts\ndeclare module \"de-indent\" {\n  function deindent(): void;\n  export = deindent; // default export\n}\n```\n\n<details>\n\n<summary>Further Discussion</summary>\n\nAny other tips? Please contribute on this topic! [We have an ongoing issue here with some references](https://github.com/typescript-cheatsheets/react/issues/8). We have more discussion and examples [in our issue here](https://github.com/typescript-cheatsheets/react/issues/12).\n\n</details>\n\n## Compilation Speed\n\nCompiling large TS projects can get slow. Here are some tips:\n\n- We have a dedicated repo tracking TS speed recommendations: https://github.com/typescript-cheatsheets/speed\n- Use [TS 3.0 Project references](https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_version#typescript-30)\n- Check the official [TS performance wiki guidelines](https://github.com/microsoft/TypeScript/wiki/Performance) - note that [Dan Rossenwasser says to take it with a grain of salt](https://news.ycombinator.com/item?id=25199070)\n- Webpack ([see CRA diff](https://gist.github.com/jaredpalmer/d3016701589f14df8a3572df91a5754b)):\n  - set `output.pathinfo = false`\n  - set `optimization.splitChunks`, `optimization.removeAvailableModules`, `optimization.removeEmptyChunks` to `false`\n"
  },
  {
    "path": "docs/advanced/patterns_by_usecase.md",
    "content": "---\nid: patterns_by_usecase\ntitle: \"Useful Patterns by Use Case\"\nsidebar_label: Useful Patterns by Use Case\n---\n\n## Wrapping/Mirroring\n\n### Wrapping/Mirroring a HTML Element\n\nUsecase: you want to make a `<Button>` that takes all the normal props of `<button>` and does extra stuff.\n\nStrategy: extend `React.ComponentPropsWithoutRef<'button'>`\n\n```tsx\n// usage\nfunction App() {\n  // Type '\"foo\"' is not assignable to type '\"button\" | \"submit\" | \"reset\" | undefined'.(2322)\n  // return <Button type=\"foo\"> sldkj </Button>\n\n  // no error\n  return <Button type=\"button\"> text </Button>;\n}\n\n// implementation\nexport interface ButtonProps extends React.ComponentPropsWithoutRef<\"button\"> {\n  specialProp?: string;\n}\nexport function Button(props: ButtonProps) {\n  const { specialProp, ...rest } = props;\n  // do something with specialProp\n  return <button {...rest} />;\n}\n```\n\n[_See this in the TS Playground_](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwCwAUI4wPQtwCuqyA5lowQ4A7fMAhC4AQTBgAFAEo4Ab0Zw4bOABUAnmCzkARAQgQDZOMHRCI8NKmA8hyAEYAbfTAhwYu-WQPOHDCeQgZwAD5wBqgcziDAMGGRBpSoWIkRnEIAJlgEwEJY2WQAdLIATADM5eXyqurslDAcUBIAPABCQSHevgC8RiYGAHxwqK7ZANYAVnBtLF3B4sP19RrWcFhQxFD1TS3tiz0+egOBS6GjMFgAHvDzR8uMAL7MDBqgYO4gWEIwyDAxEJGLdILALH8tgQ8PpHkIAArEMDoW7XHLobB4GAlADCJEghT+iIgyLaZHOITIoxUDDUqD0uGAyFcxLAAH4AFxjGBQAo8egMV4MUHQQjCUTiOBw2RgJGoLlw1moRQ0tS4cSoeBKMYMpkspEAGjgJRNqXgzzgfTgspJqAFag02S8qBI6QAFny4AB3BJunVYRnM1l7dIHOYUyVKE0lM0WljDAXPIA)\n\n**Forwarding Refs**: Most use cases will not need to obtain a ref to the inner element. When building reusable component libraries, however, `forwardRef` is often needed for exposing the underlying DOM node of an inner component to a parent component. Then you can use `ComponentPropsWithRef` to grab props for your wrapper component. Check [our docs on forwarding Refs](https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/) for more.\n\n<details>\n<summary>\n\nWhy not `ComponentProps` or `IntrinsicElements` or `[Element]HTMLAttributes` or `HTMLProps` or `HTMLAttributes`?\n\n</summary>\n\n## `ComponentProps`\n\nYou CAN use `ComponentProps` in place of `ComponentPropsWithRef`, but you may prefer to be explicit about whether or not the component's refs are forwarded, which is what we have chosen to demonstrate. The tradeoff is slightly more intimidating terminology.\n\nMore info: https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/\n\n### Maybe `React.JSX.IntrinsicElements` or `[Element]HTMLAttributes`\n\nThere are at least 2 other equivalent ways to do this, but they are more verbose:\n\n```tsx\n// Method 1: React.JSX.IntrinsicElements\ntype BtnType = React.JSX.IntrinsicElements[\"button\"]; // cannot inline or will error\nexport interface ButtonProps extends BtnType {} // etc\n\n// Method 2: React.[Element]HTMLAttributes\nexport interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>\n```\n\nLooking at [the source for `ComponentProps`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/f3134f4897c8473f590cbcdd5788da8d59796f45/types/react/index.d.ts#L821) shows that this is a clever wrapper for `React.JSX.IntrinsicElements`, whereas the second method relies on specialized interfaces with unfamiliar naming/capitalization.\n\n> Note: There are over 50 of these specialized interfaces available - look for `HTMLAttributes` in our [`@types/react` commentary](https://react-typescript-cheatsheet.netlify.app/docs/advanced/types_react_api#typesreact).\n\nUltimately, [we picked the `ComponentProps` method](https://github.com/typescript-cheatsheets/react/pull/276) as it involves the least TS specific jargon and has the most ease of use. But you'll be fine with either of these methods if you prefer.\n\n### Definitely not `React.HTMLProps` or `React.HTMLAttributes`\n\nThis is what happens when you use `React.HTMLProps`:\n\n```tsx\nexport interface ButtonProps extends React.HTMLProps<HTMLButtonElement> {\n  specialProp: string;\n}\nexport function Button(props: ButtonProps) {\n  const { specialProp, ...rest } = props;\n  // ERROR: Type 'string' is not assignable to type '\"button\" | \"submit\" | \"reset\" | undefined'.\n  return <button {...rest} />;\n}\n```\n\nIt infers a too-wide type of `string` for `type`, because it [uses `AllHTMLAttributes` under the hood](https://github.com/typescript-cheatsheets/react/issues/128#issuecomment-508103558).\n\nThis is what happens when you use `React.HTMLAttributes`:\n\n```tsx\nimport { HTMLAttributes } from \"react\";\n\nexport interface ButtonProps extends HTMLAttributes<HTMLButtonElement> {\n  /* etc */\n}\n\nfunction App() {\n  // Property 'type' does not exist on type 'IntrinsicAttributes & ButtonProps'\n  return <Button type=\"submit\"> text </Button>;\n}\n```\n\n</details>\n\n### Wrapping/Mirroring a Component\n\n> TODO: this section needs work to make it simplified.\n\nUsecase: same as above, but for a React Component you don't have access to the underlying props\n\n```tsx\nimport { CSSProperties } from \"react\";\n\nconst Box = (props: CSSProperties) => <div style={props} />;\n\nconst Card = (\n  { title, children, ...props }: { title: string } & $ElementProps<typeof Box> // new utility, see below\n) => (\n  <Box {...props}>\n    {title}: {children}\n  </Box>\n);\n```\n\nStrategy: extract a component's props by inferring them\n\nExample:\n\n```tsx\n// ReactUtilityTypes.d.ts\ndeclare type $ElementProps<T> = T extends React.ComponentType<infer Props>\n  ? Props extends object\n    ? Props\n    : never\n  : never;\n```\n\nUsage:\n\n```tsx\nimport * as Recompose from \"recompose\";\nexport const defaultProps = <\n  C extends React.ComponentType,\n  D extends Partial<$ElementProps<C>>\n>(\n  defaults: D,\n  Component: C\n): React.ComponentType<$ElementProps<C> & Partial<D>> =>\n  Recompose.defaultProps(defaults)(Component);\n```\n\n_thanks [dmisdm](https://github.com/typescript-cheatsheets/react/issues/23)_\n\n:new: You should also consider whether to explicitly forward refs:\n\n```tsx\nimport { forwardRef, ReactNode } from \"react\";\n\n// base button, with ref forwarding\ntype Props = { children: ReactNode; type: \"submit\" | \"button\" };\nexport type Ref = HTMLButtonElement;\n\nexport const FancyButton = forwardRef<Ref, Props>((props, ref) => (\n  <button ref={ref} className=\"MyCustomButtonClass\" type={props.type}>\n    {props.children}\n  </button>\n));\n```\n\n## Polymorphic Components (e.g. with `as` props)\n\n> \"Polymorphic Components\" = passing a component to be rendered, e.g. with `as` props\n\n`ElementType` is pretty useful to cover most types that can be passed to createElement e.g.\n\n```tsx\nfunction PassThrough(props: { as: React.ElementType<any> }) {\n  const { as: Component } = props;\n\n  return <Component />;\n}\n```\n\nYou might also see this with React Router:\n\n```tsx\nconst PrivateRoute = ({ component: Component, ...rest }: PrivateRouteProps) => {\n  const { isLoggedIn } = useAuth();\n\n  return isLoggedIn ? <Component {...rest} /> : <Redirect to=\"/\" />;\n};\n```\n\nFor more info you can refer to these resources:\n\n- https://blog.andrewbran.ch/polymorphic-react-components/\n- https://github.com/kripod/react-polymorphic-box\n- https://stackoverflow.com/questions/58200824/generic-react-typescript-component-with-as-prop-able-to-render-any-valid-dom\n\n[Thanks @eps1lon](https://github.com/typescript-cheatsheets/react/pull/69) and [@karol-majewski](https://github.com/typescript-cheatsheets/react/issues/151) for thoughts!\n\n## Generic Components\n\nJust as you can make generic functions and classes in TypeScript, you can also make generic components to take advantage of the type system for reusable type safety. Both Props and State can take advantage of the same generic types, although it probably makes more sense for Props than for State. You can then use the generic type to annotate types of any variables defined inside your function / class scope.\n\n```tsx\nimport { ReactNode, useState } from \"react\";\n\ninterface Props<T> {\n  items: T[];\n  renderItem: (item: T) => ReactNode;\n}\n\nfunction List<T>(props: Props<T>) {\n  const { items, renderItem } = props;\n  const [state, setState] = useState<T[]>([]); // You can use type T in List function scope.\n  return (\n    <div>\n      {items.map(renderItem)}\n      <button onClick={() => setState(items)}>Clone</button>\n      {JSON.stringify(state, null, 2)}\n    </div>\n  );\n}\n```\n\nYou can then use the generic components and get nice type safety through type inference:\n\n```tsx\nReactDOM.render(\n  <List\n    items={[\"a\", \"b\"]} // type of 'string' inferred\n    renderItem={(item) => (\n      <li key={item}>\n        {/* Error: Property 'toPrecision' does not exist on type 'string'. */}\n        {item.toPrecision(3)}\n      </li>\n    )}\n  />,\n  document.body\n);\n```\n\nAs of [TS 2.9](#typescript-29), you can also supply the type parameter in your JSX to opt out of type inference:\n\n```tsx\nReactDOM.render(\n  <List<number>\n    items={[\"a\", \"b\"]} // Error: Type 'string' is not assignable to type 'number'.\n    renderItem={(item) => <li key={item}>{item.toPrecision(3)}</li>}\n  />,\n  document.body\n);\n```\n\nYou can also use Generics using fat arrow function style:\n\n```tsx\nimport { ReactNode, useState } from \"react\";\n\ninterface Props<T> {\n  items: T[];\n  renderItem: (item: T) => ReactNode;\n}\n\n// Note the <T extends unknown> before the function definition.\n// You can't use just `<T>` as it will confuse the TSX parser whether it's a JSX tag or a Generic Declaration.\n// You can also use <T,> https://github.com/microsoft/TypeScript/issues/15713#issuecomment-499474386\nconst List = <T extends unknown>(props: Props<T>) => {\n  const { items, renderItem } = props;\n  const [state, setState] = useState<T[]>([]); // You can use type T in List function scope.\n  return (\n    <div>\n      {items.map(renderItem)}\n      <button onClick={() => setState(items)}>Clone</button>\n      {JSON.stringify(state, null, 2)}\n    </div>\n  );\n};\n```\n\nThe same for using classes: (Credit: [Karol Majewski](https://twitter.com/WrocTypeScript/status/1163234064343736326)'s [gist](https://gist.github.com/karol-majewski/befaf05af73c7cb3248b4e084ae5df71))\n\n```tsx\nimport { PureComponent, ReactNode } from \"react\";\n\ninterface Props<T> {\n  items: T[];\n  renderItem: (item: T) => ReactNode;\n}\n\ninterface State<T> {\n  items: T[];\n}\n\nclass List<T> extends PureComponent<Props<T>, State<T>> {\n  // You can use type T inside List class.\n  state: Readonly<State<T>> = {\n    items: [],\n  };\n  render() {\n    const { items, renderItem } = this.props;\n    // You can use type T inside List class.\n    const clone: T[] = items.slice(0);\n    return (\n      <div>\n        {items.map(renderItem)}\n        <button onClick={() => this.setState({ items: clone })}>Clone</button>\n        {JSON.stringify(this.state, null, 2)}\n      </div>\n    );\n  }\n}\n```\n\nThough you can't use Generic Type Parameters for Static Members:\n\n```tsx\nclass List<T> extends React.PureComponent<Props<T>, State<T>> {\n  // Static members cannot reference class type parameters.ts(2302)\n  static getDerivedStateFromProps(props: Props<T>, state: State<T>) {\n    return { items: props.items };\n  }\n}\n```\n\nTo fix this you need to convert your static function to a type inferred function:\n\n```tsx\nclass List<T> extends React.PureComponent<Props<T>, State<T>> {\n  static getDerivedStateFromProps<T>(props: Props<T>, state: State<T>) {\n    return { items: props.items };\n  }\n}\n```\n\n## Typing Children\n\nSome API designs require some restriction on `children` passed to a parent component. It is common to want to enforce these in types, but you should be aware of limitations to this ability.\n\n### What You CAN Do\n\nYou can type the **structure** of your children: just one child, or a tuple of children.\n\nThe following are valid:\n\n```ts\ntype OneChild = React.ReactNode;\ntype TwoChildren = [React.ReactNode, React.ReactNode];\ntype ArrayOfProps = SomeProp[];\ntype NumbersChildren = number[];\ntype TwoNumbersChildren = [number, number];\n```\n\n<details>\n<summary>\nDon't forget that you can also use `prop-types` if TS fails you.\n</summary>\n\n```ts\nParent.propTypes = {\n  children: PropTypes.shape({\n    props: PropTypes.shape({\n      // could share `propTypes` to the child\n      value: PropTypes.string.isRequired,\n    }),\n  }).isRequired,\n};\n```\n\n</details>\n\n### What You CANNOT Do\n\nThe thing you cannot do is **specify which components** the children are, e.g. If you want to express the fact that \"React Router `<Routes>` can only have `<Route>` as children, nothing else is allowed\" in TypeScript.\n\nThis is because when you write a JSX expression (`const foo = <MyComponent foo='foo' />`), the resultant type is blackboxed into a generic React.JSX.Element type. (_[thanks @ferdaber](https://github.com/typescript-cheatsheets/react/issues/271)_)\n\n## Type Narrowing based on Props\n\nWhat you want:\n\n```tsx\n// Usage\nfunction App() {\n  return (\n    <>\n      {/* 😎 All good */}\n      <Button target=\"_blank\" href=\"https://www.google.com\">\n        Test\n      </Button>\n      {/* 😭 Error, `disabled` doesnt exist on anchor element */}\n      <Button disabled href=\"x\">\n        Test\n      </Button>\n    </>\n  );\n}\n```\n\nHow to implement: Use [type guards](https://basarat.gitbook.io/typescript/type-system/typeguard#user-defined-type-guards)!\n\n```tsx\n// Button props\ntype ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {\n  href?: undefined;\n};\n\n// Anchor props\ntype AnchorProps = React.AnchorHTMLAttributes<HTMLAnchorElement> & {\n  href?: string;\n};\n\n// Input/output options\ntype Overload = {\n  (props: ButtonProps): React.JSX.Element;\n  (props: AnchorProps): React.JSX.Element;\n};\n\n// Guard to check if href exists in props\nconst hasHref = (props: ButtonProps | AnchorProps): props is AnchorProps =>\n  \"href\" in props;\n\n// Component\nconst Button: Overload = (props: ButtonProps | AnchorProps) => {\n  // anchor render\n  if (hasHref(props)) return <a {...props} />;\n  // button render\n  return <button {...props} />;\n};\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoAekrgCEBXGGCAOzjBzAGcKYBPMEjqNmLAAqcucALyJiMAHQMmrABIAVALIAZAIJMowAEaMkXADwady0QFEANkhBIWMAHxwAZHADeFOHAAFkSYAPwAXHD0LAAmSJjALEgxANwUAL5p5BTUcLosaIHQ7JK8AkL5hdASENwycuiKlUVQVnoGxqYWbc3QDk4u7l6+-kEhEXBcMIYsAOZZmRQ5NACSLGCMlBCMG-C1MMCsPOT8gnAA8gBuSFD2ECgx9X7kAQAUHLVckTasNdwAlJEAFIAZQAGgp+s5XFk3h9uJFelA-lxAXBQRCoYMFlllnAAOL0FBQR7MOCFJBoADWcGAmDG8TgSAAHsAplJEiVPhQ0Ed4IEUFxVCF6u9JN8RL9JHAAD55AotFFo+EcqRIlEyNyjABEwXi2tpbBVuKoNAAwrhIElXDy+cIVCxIlcbncHqKVRKHRq5erJP9NSMXnBcigFcUiLEbqM6XBXgKhSExZ9-v6iDB6FA2OYUL4FHmVelg25YcGaCYHXAI3EoKM0xms+XRLn85JC5RixkTbkAKpcFCzJAUTDRDCHNi6MBgV7+54BOuZ2OjALmLVBgIBHyUABUcEAvBuAOD28vZ7HBZhAII8t5R0kv1+YfmwYMSBzBpNqAPpGeyhqkGvWYN9AiYBFqAAd3AhQzwgWZHAUXkQG1Vd12QuB1DMGBb2XSgHyQlDNx3XdAFo9uBbCgHAoAAGjgAADGI2RQL9kmouAYggMxXCZVkpjgVg4FDKooCZRxoXgK8bzXO8HxY+jGMef832ZRDMPXNCpmU8xsMlFhcKw3D-gWIA)\n\nComponents, and JSX in general, are analogous to functions. When a component can render differently based on their props, it's similar to how a function can be overloaded to have multiple call signatures. In the same way, you can overload a function component's call signature to list all of its different \"versions\".\n\nA very common use case for this is to render something as either a button or an anchor, based on if it receives a `href` attribute.\n\n```tsx\ntype ButtonProps = React.JSX.IntrinsicElements[\"button\"];\ntype AnchorProps = React.JSX.IntrinsicElements[\"a\"];\n\n// optionally use a custom type guard\nfunction isPropsForAnchorElement(\n  props: ButtonProps | AnchorProps\n): props is AnchorProps {\n  return \"href\" in props;\n}\n\nfunction Clickable(props: ButtonProps | AnchorProps) {\n  if (isPropsForAnchorElement(props)) {\n    return <a {...props} />;\n  } else {\n    return <button {...props} />;\n  }\n}\n```\n\nThey don't even need to be completely different props, as long as they have at least one difference in properties:\n\n```tsx\ntype LinkProps = Omit<React.JSX.IntrinsicElements[\"a\"], \"href\"> & {\n  to?: string;\n};\n\nfunction RouterLink(props: LinkProps | AnchorProps) {\n  if (\"href\" in props) {\n    return <a {...props} />;\n  } else {\n    return <Link {...props} />;\n  }\n}\n```\n\n<details>\n  <summary><b>Approach: Generic Components</b></summary>\n\nHere is an example solution, see the further discussion for other solutions. _thanks to [@jpavon](https://github.com/typescript-cheatsheets/react/issues/12#issuecomment-394440577)_\n\n```tsx\ninterface LinkProps {}\ntype AnchorProps = React.AnchorHTMLAttributes<HTMLAnchorElement>;\ntype RouterLinkProps = Omit<NavLinkProps, \"href\">;\n\nconst Link = <T extends {}>(\n  props: LinkProps & T extends RouterLinkProps ? RouterLinkProps : AnchorProps\n) => {\n  if ((props as RouterLinkProps).to) {\n    return <NavLink {...(props as RouterLinkProps)} />;\n  } else {\n    return <a {...(props as AnchorProps)} />;\n  }\n};\n\n<Link<RouterLinkProps> to=\"/\">My link</Link>; // ok\n<Link<AnchorProps> href=\"/\">My link</Link>; // ok\n<Link<RouterLinkProps> to=\"/\" href=\"/\">\n  My link\n</Link>; // error\n```\n\n</details>\n\n<details>\n  <summary><b>Approach: Composition</b></summary>\n\nIf you want to conditionally render a component, sometimes it is better to use [React's composition model](https://reactjs.org/docs/composition-vs-inheritance.html) to have simpler components and better to understand typings:\n\n```tsx\ntype AnchorProps = React.AnchorHTMLAttributes<HTMLAnchorElement>;\ntype RouterLinkProps = Omit<AnchorProps, \"href\">;\n\ninterface ButtonProps {\n  as: React.ComponentClass | \"a\";\n  children?: React.ReactNode;\n}\n\nconst Button: React.FunctionComponent<ButtonProps> = (props) => {\n  const { as: Component, children, ...rest } = props;\n  return (\n    <Component className=\"button\" {...rest}>\n      {children}\n    </Component>\n  );\n};\n\nconst AnchorButton: React.FunctionComponent<AnchorProps> = (props) => (\n  <Button as=\"a\" {...props} />\n);\n\nconst LinkButton: React.FunctionComponent<RouterLinkProps> = (props) => (\n  <Button as={NavLink} {...props} />\n);\n\n<LinkButton to=\"/login\">Login</LinkButton>;\n<AnchorButton href=\"/login\">Login</AnchorButton>;\n<AnchorButton href=\"/login\" to=\"/test\">\n  Login\n</AnchorButton>; // Error: Property 'to' does not exist on type...\n```\n\n</details>\n\nYou may also want to use Discriminated Unions, please check out [Expressive React Component APIs with Discriminated Unions](https://blog.andrewbran.ch/expressive-react-component-apis-with-discriminated-unions/).\n\nHere is a brief intuition for **Discriminated Union Types**:\n\n```ts\ntype UserTextEvent = {\n  type: \"TextEvent\";\n  value: string;\n  target: HTMLInputElement;\n};\ntype UserMouseEvent = {\n  type: \"MouseEvent\";\n  value: [number, number];\n  target: HTMLElement;\n};\ntype UserEvent = UserTextEvent | UserMouseEvent;\nfunction handle(event: UserEvent) {\n  if (event.type === \"TextEvent\") {\n    event.value; // string\n    event.target; // HTMLInputElement\n    return;\n  }\n  event.value; // [number, number]\n  event.target; // HTMLElement\n}\n```\n\n<details>\n  <summary>\n  Take care: TypeScript does not narrow the type of a Discriminated Union on the basis of typeof checks. The type guard has to be on the value of a key and not its type.\n  </summary>\n\n```ts\ntype UserTextEvent = { value: string; target: HTMLInputElement };\ntype UserMouseEvent = { value: [number, number]; target: HTMLElement };\ntype UserEvent = UserTextEvent | UserMouseEvent;\nfunction handle(event: UserEvent) {\n  if (typeof event.value === \"string\") {\n    event.value; // string\n    event.target; // HTMLInputElement | HTMLElement (!!!!)\n    return;\n  }\n  event.value; // [number, number]\n  event.target; // HTMLInputElement | HTMLElement (!!!!)\n}\n```\n\nThe above example does not work as we are not checking the value of `event.value` but only its type. Read more about it [microsoft/TypeScript#30506 (comment)](https://github.com/microsoft/TypeScript/issues/30506#issuecomment-474858198)\n\n</details>\n\n<details>\n  <summary>\n  Discriminated Unions in TypeScript can also work with hook dependencies in React. The type matched is automatically updated when the corresponding union member based on which a hook depends, changes. Expand more to see an example usecase.\n   <br/><br/>\n  </summary>\n\n```tsx\nimport { useMemo } from \"react\";\n\ninterface SingleElement {\n  isArray: true;\n  value: string[];\n}\ninterface MultiElement {\n  isArray: false;\n  value: string;\n}\ntype Props = SingleElement | MultiElement;\n\nfunction Sequence(p: Props) {\n  return useMemo(\n    () => (\n      <div>\n        value(s):\n        {p.isArray && p.value.join(\",\")}\n        {!p.isArray && p.value}\n      </div>\n    ),\n    [p.isArray, p.value] // TypeScript automatically matches the corresponding value type based on dependency change\n  );\n}\n\nfunction App() {\n  return (\n    <div>\n      <Sequence isArray={false} value={\"foo\"} />\n      <Sequence isArray={true} value={[\"foo\", \"bar\", \"baz\"]} />\n    </div>\n  );\n}\n```\n\n<a href=\"https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8dccAD5wA3vwETgqAIJQoyJgC44MKAFcs9CRIBuyADYblqVcAB2AcwDaAXRpxxAgL7jhY7QKmz5SuAQOomo66BkZwJlDmFloSTvS4EGYmcAAacDxwABRgypwQ3ACU6QB8ouKUMGpQZphUMAB0aoEAslggEJnBmUU8pZ0ecAA8ACbAOsXB2nqGWJmoBYqTEiJg9V5yCnAAZFtwq9Ma9QBWEOaZZAA0ZAUuAwIiAISr6z7bu-uhWLcegwD0o+NggULsErM8ZBsmBc9vUDlgbNDfr84AAVFhYVC4SJgeDINQwEjIGDAXAGfRMOAgIm4AAWGJUdLgCTkGMgZlGljgcJU6PEBXocToBDUZnwwEScGkYDA3TKAgqVRq-QkIzGTP0aFQADlkCAsDwAERSsAGiYDQZpF4KHgifz6QJOLmfG1kAgQCBkR2-M0-S0Qnw21QaR1wm1WV3uy7kABGyCgUbIsYAXmQbF6fQI-gCffy6E4gA\"><i>See this in TS Playground</i>\n</a>\n\nIn the above example, based on the `isArray` union member, the type of the `value` hook dependency changes.\n\n </details>\n\nTo streamline this you may also combine this with the concept of **User-Defined Type Guards**:\n\n```ts\nfunction isString(a: unknown): a is string {\n  return typeof a === \"string\";\n}\n```\n\n[Read more about User-Defined Type Guards in the Handbook](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards).\n\n### Narrowing using `extends`\n\nSee this quick guide: https://twitter.com/mpocock1/status/1500813765973053440?s=20&t=ImUA-NnZc4iUuPDx-XiMTA\n\n## Props: One or the other but not both\n\nSince TypeScript is a structural type system, _minimum_ property requirements are described rather than _exact_, which makes it a bit more difficult to disallow certain props compared to what you might think. `never` can be used to allow either one or another prop, but not both:\n\n```tsx\ntype Props1 = { foo: string; bar?: never };\ntype Props2 = { bar: string; foo?: never };\n\nconst OneOrTheOther = (props: Props1 | Props2) => {\n  if (\"foo\" in props && typeof props.foo === \"string\") {\n    // `props.bar` is of type `undefined`\n    return <>{props.foo}</>;\n  }\n  // `props.foo` is of type `undefined`\n  return <>{props.bar}</>;\n};\nconst Component = () => (\n  <>\n    <OneOrTheOther /> {/* error */}\n    <OneOrTheOther foo=\"\" /> {/* ok */}\n    <OneOrTheOther bar=\"\" /> {/* ok */}\n    <OneOrTheOther foo=\"\" bar=\"\" /> {/* error */}\n  </>\n);\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOABRzAGcBGOAXjgG85MIIAXHCYwowAHYBzANxwARiigB+IeKQA3JFDgBfaRWq0GEZgCYO3eYqEixU2Xwgq4azdr3k0EcSLgB5NT8oABUACyQ-GHDtTgAKMEYmIWNmNgAfekTTAEoOAD5uUjg4YEw4WPxHfBLxOASTJjgAMia4KhoIMvrmADpHDnZOfFsJSXxcriLiuAB6GbgAA26mHoUoBZLGzrbDRYBXcQATJEwJJEOFqeKiGD2oWoAePK5lvv4dB5m8-WKdKbnFq9HBtgFsyu1aAsDsdTmoLlMbndHs9XmsPl99B4vD54ABhXCQNTieBxXLsAqxKZPK5wB4BCIhcKRaKzApcGYAKjgWhw2g5Mz+01p9KCYQiUS0vH47Hw1S+3E5cAgAGs4PzBdM6YFGeKWWsZXK2YqVWqBTStQyxczJY4DVYoHb5eyuTzoKaNZ88qRstIgA).\n\nA better alternative might be to use a discriminant prop like this:\n\n```tsx\ntype Props1 = { type: \"foo\"; foo: string };\ntype Props2 = { type: \"bar\"; bar: string };\n\nconst OneOrTheOther = (props: Props1 | Props2) => {\n  if (props.type === \"foo\") {\n    // `props.bar` does not exist\n    return <>{props.foo}</>;\n  }\n  // `props.foo` does not exist\n  return <>{props.bar}</>;\n};\nconst Component = () => (\n  <>\n    <OneOrTheOther type=\"foo\" /> {/* error */}\n    <OneOrTheOther type=\"foo\" foo=\"\" /> {/* ok */}\n    <OneOrTheOther type=\"foo\" bar=\"\" /> {/* error */}\n    <OneOrTheOther type=\"foo\" foo=\"\" bar=\"\" /> {/* error */}\n    <OneOrTheOther type=\"bar\" /> {/* error */}\n    <OneOrTheOther type=\"bar\" foo=\"\" /> {/* error */}\n    <OneOrTheOther type=\"bar\" bar=\"\" /> {/* ok */}\n    <OneOrTheOther type=\"bar\" foo=\"\" bar=\"\" /> {/* error */}\n  </>\n);\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOABRzAGcBGOAXjgG84qaAuApggR8AbjjCIgpjCjAAdgHM4AXzEVqtBhGYAmDt15bB+AEYoo4uBagy5ilevJoIC2XADyCpJ6gAVAAtfGGCoQwAKMEYmQR1mNgAfehi9AEoOAD5uUjg4YEw4KJiAOj5adkqhEXwMrly8uAB6JrgAA2jdJhLbNrgAEwgkJjgFCHgkAA9gWQa8ohgAVygFOAAeTK5O5hKpVTWmzI081QaW9u3uqT7B4dHxuCmZmAaF5dWNrdLbfcONZ1c7ngAGFcJAfAp4JwIhl2NkIg0NnN1t5fAFgp5QkhwuV2PgpPhmtkuE0AFSPKA4cKkpqnRoonx+IIhMLGGh4gmSER4wmHbhkuAQADWcBpdMaa1RTIxWJxWg5NRslh5RP55OxVNFtORksZ6JZ2LZSAVoi5EBVthVfJJ6sp0C14ryurRzMxrNx5ksvOJAo19rFOql+rdho9tkJUitPttmoD9Od0oNcvZnqsSqgUbVgpFcYlQddsqNePDZotyvw3qzfup2qdh1IaTEQA).\n\n## Props: Pass all or nothing\n\nPassing no props is equivalent to passing an empty object. However, the type for an empty object is not `{}`, which you might think. [Make sure you understand what empty interface, `{}` and `Object` means](/docs/basic/getting-started/basic_type_example#empty-interface--and-object). `Record<string, never>` is probably the closest you can get to an empty object type, and is [recommended by typescript-eslint](https://typescript-eslint.io/rules/ban-types/). Here's an example of allowing \"nothing or all\":\n\n```tsx\ninterface All {\n  a: string;\n  b: string;\n}\n\ntype Nothing = Record<string, never>;\n\nconst AllOrNothing = (props: All | Nothing) => {\n  if (\"a\" in props) {\n    return <>{props.b}</>;\n  }\n  return <>Nothing</>;\n};\n\nconst Component = () => (\n  <>\n    <AllOrNothing /> {/* ok */}\n    <AllOrNothing a=\"\" /> {/* error */}\n    <AllOrNothing b=\"\" /> {/* error */}\n    <AllOrNothing a=\"\" b=\"\" /> {/* ok */}\n  </>\n);\n```\n\nWhile this works, representing an empty object with `Record<string, never>` [is not officially recommended](https://github.com/microsoft/TypeScript/issues/47486#issuecomment-1015671856). It might be better approaching this in another way, to avoid trying to type \"an exactly empty object\". One way is grouping the required props in an optional object:\n\n```tsx\ninterface Props {\n  obj?: {\n    a: string;\n    b: string;\n  };\n}\n\nconst AllOrNothing = (props: Props) => {\n  if (props.obj) {\n    return <>{props.obj.a}</>;\n  }\n  return <>Nothing</>;\n};\n\nconst Component = () => (\n  <>\n    <AllOrNothing /> {/* ok */}\n    <AllOrNothing obj={{ a: \"\" }} /> {/* error */}\n    <AllOrNothing obj={{ b: \"\" }} /> {/* error */}\n    <AllOrNothing obj={{ a: \"\", b: \"\" }} /> {/* ok */}\n  </>\n);\n```\n\nAnother way is to make both props optional and then check that either none or all props are passed at runtime.\n\n## Props: Pass One ONLY IF the Other Is Passed\n\nSay you want a Text component that gets truncated if `truncate` prop is passed but expands to show the full text when `expanded` prop is passed (e.g. when the user clicks the text).\n\nYou want to allow `expanded` to be passed only if `truncate` is also passed, because there is no use for `expanded` if the text is not truncated.\n\nUsage example:\n\n```tsx\nconst App = () => (\n  <>\n    {/* these all typecheck */}\n    <Text>not truncated</Text>\n    <Text truncate>truncated</Text>\n    <Text truncate expanded>\n      truncate-able but expanded\n    </Text>\n    {/* TS error: Property 'truncate' is missing in type '{ children: string; expanded: true; }' but required in type '{ truncate: true; expanded?: boolean | undefined; }'. */}\n    <Text expanded>truncate-able but expanded</Text>\n  </>\n);\n```\n\nYou can implement this by function overloads:\n\n```tsx\nimport { ReactNode } from \"react\";\n\ninterface CommonProps {\n  children?: ReactNode;\n  miscProps?: any;\n}\n\ntype NoTruncateProps = CommonProps & { truncate?: false };\n\ntype TruncateProps = CommonProps & { truncate: true; expanded?: boolean };\n\n// Function overloads to accept both prop types NoTruncateProps & TruncateProps\nfunction Text(props: NoTruncateProps): React.JSX.Element;\nfunction Text(props: TruncateProps): React.JSX.Element;\nfunction Text(props: CommonProps & { truncate?: boolean; expanded?: boolean }) {\n  const { children, truncate, expanded, ...otherProps } = props;\n  const classNames = truncate ? \".truncate\" : \"\";\n  return (\n    <div className={classNames} aria-expanded={!!expanded} {...otherProps}>\n      {children}\n    </div>\n  );\n}\n```\n\n## Props: Omit prop from a type\n\nNote: [Omit was added as a first class utility in TS 3.5](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittk)! 🎉\n\nSometimes when intersecting types, we want to define our own version of a prop. For example, I want my component to have a `label`, but the type I am intersecting with also has a `label` prop. Here's how to extract that out:\n\n```tsx\nexport interface Props {\n  label: React.ReactNode; // this will conflict with the InputElement's label\n}\n\n// this comes inbuilt with TS 3.5\ntype Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;\n\n// usage\nexport const Checkbox = (\n  props: Props & Omit<React.HTMLProps<HTMLInputElement>, \"label\">\n) => {\n  const { label } = props;\n  return (\n    <div className=\"Checkbox\">\n      <label className=\"Checkbox-label\">\n        <input type=\"checkbox\" {...props} />\n      </label>\n      <span>{label}</span>\n    </div>\n  );\n};\n```\n\nWhen your component defines multiple props, chances of those conflicts increase. However you can explicitly state that all your fields should be removed from the underlying component using the `keyof` operator:\n\n```tsx\nexport interface Props {\n  label: React.ReactNode; // conflicts with the InputElement's label\n  onChange: (text: string) => void; // conflicts with InputElement's onChange\n}\n\nexport const Textbox = (\n  props: Props & Omit<React.HTMLProps<HTMLInputElement>, keyof Props>\n) => {\n  // implement Textbox component ...\n};\n```\n\nAs you can see from the Omit example above, you can write significant logic in your types as well. [type-zoo](https://github.com/pelotom/type-zoo) is a nice toolkit of operators you may wish to check out (includes Omit), as well as [utility-types](https://github.com/piotrwitek/utility-types) (especially for those migrating from Flow).\n\n## Props: Extracting Prop Types of a Component\n\nSometimes you want the prop types of a component, but it isn't exported.\n\nA simple solution is to use `React.ComponentProps`:\n\n```tsx\n// a Modal component defined elsewhere\nconst defaultProps: React.ComponentProps<typeof Modal> = {\n  title: \"Hello World\",\n  visible: true,\n  onClick: jest.fn(),\n};\n```\n\nThere are advanced edge cases if you want to extract the prop types of a component taking into account internal props, `propTypes`, and `defaultProps` - [check our issue here for helper utilities that resolve these](https://github.com/typescript-cheatsheets/react/issues/63).\n\n## Props: Render Props\n\n> Advice: Where possible, you should try to use Hooks instead of Render Props. We include this merely for completeness.\n\nSometimes you will want to write a function that can take a React element or a string or something else as a prop. The best Type to use for such a situation is `ReactNode` which fits anywhere a normal, well, React Node would fit:\n\n```tsx\nimport { ReactNode } from \"react\";\n\ninterface Props {\n  label?: ReactNode;\n  children?: ReactNode;\n}\n\nconst Card = ({ children, label }: Props) => {\n  return (\n    <div>\n      {label && <div>{label}</div>}\n      {children}\n    </div>\n  );\n};\n```\n\nIf you are using a function-as-a-child render prop:\n\n```tsx\nimport { ReactNode } from \"react\";\n\ninterface Props {\n  children: (foo: string) => ReactNode;\n}\n```\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new/choose).\n\n## Handling Exceptions\n\nYou can provide good information when bad things happen.\n\n```ts\nclass InvalidDateFormatError extends RangeError {}\nclass DateIsInFutureError extends RangeError {}\n\n/**\n * // optional docblock\n * @throws {InvalidDateFormatError} The user entered date incorrectly\n * @throws {DateIsInFutureError} The user entered date in future\n *\n */\nfunction parse(date: string) {\n  if (!isValid(date))\n    throw new InvalidDateFormatError(\"not a valid date format\");\n  if (isInFuture(date)) throw new DateIsInFutureError(\"date is in the future\");\n  // ...\n}\n\ntry {\n  // call parse(date) somewhere\n} catch (e) {\n  if (e instanceof InvalidDateFormatError) {\n    console.error(\"invalid date format\", e);\n  } else if (e instanceof DateIsInFutureError) {\n    console.warn(\"date is in future\", e);\n  } else {\n    throw e;\n  }\n}\n```\n\n[View in TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BJAOwDcVrgATAERRhIAYtBACAolBxQ4SAB6CW3RghQsA5kknS4AbwC+VWgzj9BTOqyEBXGNaLboshUiUq1mxzIMUKmaywYwBAscMB0AGqcPAAU3AJIAFxwdDBQwBoAlHoUcHBEdlCh8YJwAPxwadZIcMmYnHRIANwUhpTk-oEwwaHhVrb2SHEJyanpWTnkeWghqXAlSAByEADucAC8cCxIa2ZDmS1TcDMsc2j2RCwwextbO6YJw4KZuXCvBfah51Ku1wkAdJoYAAVUD7OAAPnmCWWK0BSBBYJiB1avnIAHoAFSY3KYuDo9FwCBgbohTjzCBoABG1EpAGtcXAAAIwAAWOBWjF0rA4XD4CREUDEMC8+jgwNZNWsjRkvyQRG40NKGRmPww1AAnoyWezVly9hZ+oUtFJoGKJVKZbIrvKkIqFmFQv5jbjcei-AEgiE4GAUFBGk8kik0hl1NldK9gJg4DEAIThKJ8wOZF5HPJsjl3NY86L8wSC4VeGIAIhYEHgKDgvJ4SpqmFEAmLKKOUZjfRYNmNyeyGdWWYe5ksHYGDlNUBLDvCjsqkrgzsGTcOeQJcH+a9R7TSGsmy8JaE41B9foDC2ydFwO0lRFaxwEaFZMaQ4cj0ZiNQyqTUaCQEGjOb5ewFhIY7PmmxyzBA1BIP88rSCWGTVvaCRzg2MDFgANLIzZ5GKSDUI0YSvu+pwwF+P7RgaQ6doMXigXk0wQVB-wrH6LATshU4ZHOI5IBhWFLnAuH4TUEZgb2azNK8bT6EAA)\n\nSimply throwing an exception is fine, however it would be nice to make TypeScript remind the consumer of your code to handle your exception. We can do that just by returning instead of throwing:\n\n```ts\nfunction parse(\n  date: string\n): Date | InvalidDateFormatError | DateIsInFutureError {\n  if (!isValid(date))\n    return new InvalidDateFormatError(\"not a valid date format\");\n  if (isInFuture(date)) return new DateIsInFutureError(\"date is in the future\");\n  // ...\n}\n\n// now consumer *has* to handle the errors\nlet result = parse(\"mydate\");\nif (result instanceof InvalidDateFormatError) {\n  console.error(\"invalid date format\", result.message);\n} else if (result instanceof DateIsInFutureError) {\n  console.warn(\"date is in future\", result.message);\n} else {\n  /// use result safely\n}\n\n// alternately you can just handle all errors\nif (result instanceof Error) {\n  console.error(\"error\", result);\n} else {\n  /// use result safely\n}\n```\n\nYou can also describe exceptions with special-purpose data types (don't say monads...) like the `Try`, `Option` (or `Maybe`), and `Either` data types:\n\n```ts\ninterface Option<T> {\n  flatMap<U>(f: (value: T) => None): None;\n  flatMap<U>(f: (value: T) => Option<U>): FormikOption<U>;\n  getOrElse(value: T): T;\n}\nclass Some<T> implements Option<T> {\n  constructor(private value: T) {}\n  flatMap<U>(f: (value: T) => None): None;\n  flatMap<U>(f: (value: T) => Some<U>): Some<U>;\n  flatMap<U>(f: (value: T) => Option<U>): Option<U> {\n    return f(this.value);\n  }\n  getOrElse(): T {\n    return this.value;\n  }\n}\nclass None implements Option<never> {\n  flatMap<U>(): None {\n    return this;\n  }\n  getOrElse<U>(value: U): U {\n    return value;\n  }\n}\n\n// now you can use it like:\nlet result = Option(6) // Some<number>\n  .flatMap((n) => Option(n * 3)) // Some<number>\n  .flatMap((n = new None())) // None\n  .getOrElse(7);\n\n// or:\nlet result = ask() // Option<string>\n  .flatMap(parse) // Option<Date>\n  .flatMap((d) => new Some(d.toISOString())) // Option<string>\n  .getOrElse(\"error parsing string\");\n```\n"
  },
  {
    "path": "docs/advanced/patterns_by_version.md",
    "content": "---\nid: patterns_by_version\ntitle: \"Useful Patterns by TypeScript Version\"\nsidebar_label: Useful Patterns by TypeScript Version\n---\n\nTypeScript Versions often introduce new ways to do things; this section helps current users of React + TypeScript upgrade TypeScript versions and explore patterns commonly used by TypeScript + React apps and libraries. This may have duplications with other sections; if you spot any discrepancies, [file an issue](https://github.com/typescript-cheatsheets/react/issues/new)!\n\n_TypeScript version guides before 2.9 are unwritten, please feel free to send a PR!_ Apart from official TS team communication we also recommend [Marius Schulz's blog for version notes](https://mariusschulz.com/). For more TypeScript history, see [A Brief History of TypeScript Types](https://github.com/blakeembrey/a-brief-history-of-types-with-typescript) and [A Brief History of DefinitelyTyped](https://blog.johnnyreilly.com/2019/10/definitely-typed-movie.html). You may also wish to explore lesser known alternative typings of React like [prop-types](https://reactjs.org/docs/typechecking-with-proptypes.html), [om](https://github.com/omcljs/om), [reason-react](https://reasonml.github.io/reason-react/), and [typed-react](https://github.com/asana/typed-react).\n\n## TypeScript 2.9\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html) | [Blog Post](https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/)]\n\n1. Type arguments for tagged template strings (e.g. `styled-components`):\n\n```tsx\nexport interface InputFormProps {\n  foo: string; // this is understood inside the template string below\n}\n\nexport const InputForm = styledInput<InputFormProps>`\n    color:\n        ${({ themeName }) => (themeName === \"dark\" ? \"black\" : \"white\")};\n    border-color: ${({ foo }) => (foo ? \"red\" : \"black\")};\n`;\n```\n\n2. **JSX Generics**\n\nhttps://github.com/Microsoft/TypeScript/pull/22415\n\nHelps with typing/using generic components:\n\n```tsx\n// instead of\n<Formik\n  render={(props: FormikProps<Values>) => {\n    /* your code here ... */\n  }}\n/>;\n\n// usage\n<Formik<Values>\n  render={(props) => {\n    /* your code here ... */\n  }}\n/>;\n<MyComponent<number> data={12} />;\n```\n\nMore info: https://github.com/basarat/typescript-book/blob/master/docs/jsx/react.md#react-jsx-tip-generic-components\n\n## TypeScript 3.0\n\n[[Release Notes](https://github.com/Microsoft/TypeScript/releases/tag/v3.0.1) | [Blog Post](https://blogs.msdn.microsoft.com/typescript/2018/07/30/announcing-typescript-3-0/)]\n\n1. Typed rest parameters for writing arguments of variable length:\n\n```ts\n// `rest` accepts any number of strings - even none!\nfunction foo(...rest: string[]) {\n  // ...\n}\n\nfoo(\"hello\"); // works\nfoo(\"hello\", \"world\"); // also works\n```\n\n2. Support for `propTypes` and `static defaultProps` in JSX using `LibraryManagedAttributes`:\n\n```tsx\nexport interface Props {\n  name: string;\n}\n\nexport class Greet extends React.Component<Props> {\n  render() {\n    const { name } = this.props;\n    return <div>Hello ${name.toUpperCase()}!</div>;\n  }\n  static defaultProps = { name: \"world\" };\n}\n\n// Type-checks! No type assertions needed!\nlet el = <Greet />;\n```\n\n3. new `Unknown` type\n\nFor typing API's to force type checks - not specifically React related, however very handy for dealing with API responses:\n\n```tsx\ninterface IComment {\n  date: Date;\n  message: string;\n}\n\ninterface IDataService1 {\n  getData(): any;\n}\n\nlet service1: IDataService1;\nconst response = service1.getData();\nresponse.a.b.c.d; // RUNTIME ERROR\n\n// ----- compare with -------\n\ninterface IDataService2 {\n  getData(): unknown; // ooo\n}\n\nlet service2: IDataService2;\nconst response2 = service2.getData();\n// response2.a.b.c.d; // COMPILE TIME ERROR if you do this\n\nif (typeof response === \"string\") {\n  console.log(response.toUpperCase()); // `response` now has type 'string'\n}\n```\n\nTODO: blame this change. Don't know what this should've done\n\nYou can also assert a type, or use a **type guard** against an `unknown` type. This is better than resorting to `any`.\n\n4. Project References\n\nProject references allow TypeScript projects to depend on other TypeScript projects – specifically, allowing tsconfig.json files to reference other tsconfig.json files. This lets large codebases scale without recompiling every part of the codebase every time, by breaking it up into multiple projects.\n\nIn each folder, create a tsconfig.json that includes at least:\n\n```json\n{\n  \"compilerOptions\": {\n    \"composite\": true, // tells TSC it is a subproject of a larger project\n    \"declaration\": true, // emit .d.ts declaration files since project references dont have access to source ts files. important for project references to work!\n    \"declarationMap\": true, // sourcemaps for .d.ts\n    \"rootDir\": \".\" // specify compile it relative to root project at .\n  },\n  \"include\": [\"./**/*.ts\"],\n  \"references\": [\n    // (optional) array of subprojects your subproject depends on\n    {\n      \"path\": \"../myreferencedproject\", // must have tsconfig.json\n      \"prepend\": true // concatenate js and sourcemaps generated by this subproject, if and only if using outFile\n    }\n  ]\n}\n```\n\nand the root `tsconfig.json` that references top level subproject:\n\n```json\n{\n  \"files\": [],\n  \"references\": [{ \"path\": \"./proj1\" }, { \"path\": \"./proj2\" }]\n}\n```\n\nand you must run `tsc --build` or `tsc -b`.\n\nTo save the tsconfig boilerplate, you can use the `extends` option:\n\n```json\n{\n  \"extends\": \"../tsconfig.base\"\n  // more stuff here\n}\n```\n\n## TypeScript 3.1\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html) | [Blog Post](https://blogs.msdn.microsoft.com/typescript/announcing-typescript-3-1/)]\n\n1. Properties declarations on functions\n\nAttaching properties to functions like this \"just works\" now:\n\n```tsx\nexport const FooComponent = ({ name }) => <div>Hello! I am {name}</div>;\n\nFooComponent.defaultProps = {\n  name: \"swyx\",\n};\n```\n\n## TypeScript 3.2\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-2.html) | [Blog Post](https://blogs.msdn.microsoft.com/typescript/2018/11/29/announcing-typescript-3-2/)]\n\nnothing specifically React related.\n\n## TypeScript 3.3\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-3.html) | [Blog Post](https://blogs.msdn.microsoft.com/typescript/2019/01/31/announcing-typescript-3-3/)]\n\nnothing specifically React related.\n\n## TypeScript 3.4\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4)]\n\n1. [`const` assertions](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions)\n\n```tsx\nfunction useLoading() {\n  const [isLoading, setState] = useState(false);\n\n  const load = (aPromise: Promise<any>) => {\n    setState(true);\n    return aPromise.finally(() => setState(false));\n  };\n\n  return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]\n}\n```\n\nMore info on places you can use [const assertions](https://blog.logrocket.com/const-assertions-are-the-killer-new-typescript-feature-b73451f35802).\n\n## TypeScript 3.5\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-5/)]\n\n1. Built-in `<Omit>` Type!!\n\n2. Higher order type inference from generic constructors\n\n```tsx\ntype ComponentClass<P> = new (props: P) => Component<P>;\ndeclare class Component<P> {\n  props: P;\n  constructor(props: P);\n}\n\ndeclare function myHoc<P>(C: ComponentClass<P>): ComponentClass<P>;\n\ntype NestedProps<T> = { foo: number; stuff: T };\n\ndeclare class GenericComponent<T> extends Component<NestedProps<T>> {}\n\n// type is 'new <T>(props: NestedProps<T>) => Component<NestedProps<T>>'\nconst GenericComponent2 = myHoc(GenericComponent);\n```\n\nSee also [Notes from Google upgrading to 3.5](https://github.com/microsoft/TypeScript/issues/33272)\n\n## TypeScript 3.6\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-6.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-6/)]\n\nNothing particularly React specific but [the playground](https://github.com/agentcooper/typescript-play) got an upgrade and [Ambient Classes and Functions Can Merge](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-6.html#ambient-classes-and-functions-can-merge)\n\n## TypeScript 3.7\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/)]\n\n1. Optional Chaining\n\n```ts\nlet x = foo?.bar.baz();\n\n// is equivalent to\n\nlet x = foo === null || foo === undefined ? undefined : foo.bar.baz();\n\n// Optional Element access\nfunction tryGetFirstElement<T>(arr?: T[]) {\n  return arr?.[0];\n}\n\n// Optional Call\nasync function makeRequest(url: string, log?: (msg: string) => void) {\n  log?.(`Request started at ${new Date().toISOString()}`);\n  const result = (await fetch(url)).json();\n  log?.(`Request finished at at ${new Date().toISOString()}`);\n  return result;\n}\n```\n\n2. Nullish Coalescing\n\n```ts\nlet x = foo ?? bar();\n\n// equivalent to\n\nlet x = foo !== null && foo !== undefined ? foo : bar();\n```\n\n**YOU SHOULD USUALLY USE `??` WHEREVER YOU NORMALLY USE `||`** unless you truly mean falsiness:\n\n```tsx\nfunction ShowNumber({ value }: { value: number }) {\n  let _value = value || 0.5; // will replace 0 with 0.5 even if user really means 0\n  // etc...\n}\n```\n\n3. Assertion Functions\n\n```tsx\nfunction assert(condition: any, msg?: string): asserts condition {\n  if (!condition) {\n    throw new AssertionError(msg);\n  }\n}\nfunction yell(str) {\n  assert(typeof str === \"string\");\n\n  return str.toUppercase();\n  //         ~~~~~~~~~~~\n  // error: Property 'toUppercase' does not exist on type 'string'.\n  //        Did you mean 'toUpperCase'?\n}\n```\n\nYou can also assert without a custom function:\n\n```tsx\nfunction assertIsString(val: any): asserts val is string {\n  if (typeof val !== \"string\") {\n    throw new AssertionError(\"Not a string!\");\n  }\n}\nfunction yell(str: any) {\n  assertIsString(str);\n\n  // Now TypeScript knows that 'str' is a 'string'.\n\n  return str.toUppercase();\n  //         ~~~~~~~~~~~\n  // error: Property 'toUppercase' does not exist on type 'string'.\n  //        Did you mean 'toUpperCase'?\n}\n```\n\n4. `ts-nocheck`\n\nYou can now add `// @ts-nocheck` to the top of TypeScript files! good for migrations.\n\n## TypeScript 3.8\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-8/)]\n\n1. Type-Only Imports and Exports\n\n```ts\nimport type { SomeThing } from \"./some-module.js\";\n\nexport type { SomeThing };\n```\n\n2. ECMAScript Private Fields\n\nNot really React specific but ok Bloomberg\n\n3. `export * as ns` Syntax\n\nThis is ES2020 syntax. Instead of\n\n```js\nimport * as utilities from \"./utilities.js\";\nexport { utilities };\n```\n\nyou can do\n\n```js\nexport * as utilities from \"./utilities.js\";\n```\n\n4. Top-Level `await`\n\nnot React specific but gj Myles\n\n5. JSDoc Property Modifiers\n\nhandy for JSDoc users - `@public, @private, @protected, @readonly`\n\n6. Better Directory Watching on Linux and watchOptions\n7. “Fast and Loose” Incremental Checking\n\n`assumeChangesOnlyAffectDirectDependencies` reduces build times for extremely large codebases.\n\n## TypeScript 3.9\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/)]\n\n1. (minor feature) New `ts-expect-error` directive.\n\nUse this when writing tests you expect to error.\n\n```ts\n// @ts-expect-error\nconsole.log(47 * \"octopus\");\n```\n\nPick `ts-expect-error` if:\n\n- you’re writing test code where you actually want the type system to error on an operation\n- you expect a fix to be coming in fairly quickly and you just need a quick workaround\n- you’re in a reasonably-sized project with a proactive team that wants to remove suppression comments as soon affected code is valid again\n\nPick `ts-ignore` if:\n\n- you have an a larger project and and new errors have appeared in code with no clear owner\n- you are in the middle of an upgrade between two different versions of TypeScript, and a line of code errors in one version but not another.\n- you honestly don’t have the time to decide which of these options is better.\n\n2. `}` and `>` are Now Invalid JSX Text Characters\n\nThey were always invalid, but now TypeScript and Babel are enforcing it:\n\n```\nUnexpected token. Did you mean `{'>'}` or `&gt;`?\nUnexpected token. Did you mean `{'}'}` or `&rbrace;`?\n```\n\nYou can [convert these in bulk](https://github.com/microsoft/TypeScript/pull/37436) if needed.\n\n## TypeScript 4.0\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-4-0/)]\n\n- [Variadic Tuple Types](https://devblogs.microsoft.com/typescript/announcing-typescript-4-0-beta/#variadic-tuple-types)\n\n  - useful for [simplified Reducer-like State](https://www.reddit.com/r/reactjs/comments/hu0ytg/simplified_reducerlike_state_using_typescript_40/)\n\n- [Custom JSX Factories](https://devblogs.microsoft.com/typescript/announcing-typescript-4-0/#custom-jsx-factories)\n\nIt's for custom pragmas with Preact\n\n```tsx\n// Note: these pragma comments need to be written\n// with a JSDoc-style multiline syntax to take effect.\n/** @jsx h */\n/** @jsxFrag Fragment */\n\nimport { h, Fragment } from \"preact\";\n\nlet stuff = (\n  <>\n    <div>Hello</div>\n  </>\n);\n// transformed to\nlet stuff = h(Fragment, null, h(\"div\", null, \"Hello\"));\n```\n\n## TypeScript 4.1\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/)]\n\n1. Template Literal Types\n\nThis is a HUGE feature.\n\nUsecase 1 - Generating string literal types from permutations of other string literal types:\n\n```tsx\ntype VerticalAlignment = \"top\" | \"middle\" | \"bottom\";\ntype HorizontalAlignment = \"left\" | \"center\" | \"right\";\n\n// Takes\n//   | \"top-left\"    | \"top-center\"    | \"top-right\"\n//   | \"middle-left\" | \"middle-center\" | \"middle-right\"\n//   | \"bottom-left\" | \"bottom-center\" | \"bottom-right\"\ndeclare function setAlignment(\n  value: `${VerticalAlignment}-${HorizontalAlignment}`\n): void;\n\nsetAlignment(\"top-left\"); // works!\nsetAlignment(\"top-middel\"); // error!\nsetAlignment(\"top-pot\"); // error! but good doughnuts if you're ever in Seattle\n```\n\nUsecase 2 - Modeling dynaming string literal types:\n\n```tsx\ntype PropEventSource<T> = {\n  on(eventName: `${string & keyof T}Changed`, callback: () => void): void;\n};\n\n/// Create a \"watched object\" with an 'on' method\n/// so that you can watch for changes to properties.\ndeclare function makeWatchedObject<T>(obj: T): T & PropEventSource<T>;\n```\n\nTo make string manipulation easier there are new generics: `Uppercase`, `Lowercase`, `Capitalize` and `Uncapitalize`.\n\nYou can combine it with the `infer` keyword [like this](https://www.smashingmagazine.com/2021/01/dynamic-static-typing-typescript/#conditional-types-and-recursive-template-literal-types):\n\n```ts\ntype ParseRouteParams<Rte> = Rte extends `${string}/:${infer P}` ? P : never;\n\ntype Params = ParseRouteParams<\"/api/user/:userID\">; // Params is \"userID\"\n\ntype NoParams = ParseRouteParams<\"/api/user\">; // NoParams is never --> no params!\n```\n\nThis feature is extremely flexible, see other usecase ideas here:\n\n- https://hasura.io/blog/how-typescript-template-literal-types-helped-us-with-multiple-database-support/\n- https://github.com/ghoullier/awesome-template-literal-types\n\n2. [React 17 jsx Factories](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#react-17-jsx-factories)\n\nThis is a new compiler option to offer output inline with React 17 support in general:\n\n```jsx\n// ./src/tsconfig.json - for production\n{\n    \"compilerOptions\": {\n        \"module\": \"esnext\",\n        \"target\": \"es2015\",\n        \"jsx\": \"react-jsx\",\n        \"strict\": true\n    },\n    \"include\": [\n        \"./**/*\"\n    ]\n}\n\n// ./src/tsconfig.dev.json - for development - extending the production config\n{\n    \"extends\": \"./tsconfig.json\",\n    \"compilerOptions\": {\n        \"jsx\": \"react-jsxdev\"\n    }\n}\n```\n\nMisc\n\n2. [Key Remapping in Mapped Types](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#key-remapping-in-mapped-types)\n3. [Recursive Conditional Types](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#recursive-conditional-types)\n4. [Checked Indexed Accesses](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#checked-indexed-accesses-nouncheckedindexedaccess)\n\n## TypeScript 4.2\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-4-2/)]\n\nnothing react specific\n\n## TypeScript 4.3\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-3.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-4-3/)]\n\nnothing react specific\n\n## TypeScript 4.4\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-4.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-4-4/)]\n\nnothing react specific\n\n## TypeScript 4.5\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/)]\n\n1. (minor VSCode improvement) Snippet Completions for JSX Attributes\n\n## TypeScript 4.6\n\n[[Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-6.html) | [Blog Post](https://devblogs.microsoft.com/typescript/announcing-typescript-4-6/)]\n\n1. (extremely minor) Removed Unnecessary Arguments in `react-jsx` compile output\n\n## TypeScript Roadmap and Spec\n\nhttps://github.com/Microsoft/TypeScript/wiki/Roadmap\n\nDid you also know you can read the TypeScript spec online?? https://github.com/microsoft/TypeScript/blob/master/doc/spec-ARCHIVED.md\n"
  },
  {
    "path": "docs/advanced/types-react-ap.md",
    "content": "---\nid: types_react_api\ntitle: \"Section 4: @types/react and @types/react-dom APIs\"\nsidebar_label: \"@types/react and @types/react-dom APIs\"\n---\n\nThe `@types` typings export both \"public\" types meant for your use as well as \"private\" types that are for internal use.\n\nCheck [SaltyCrane's React TypeScript Cheatsheet](https://github.com/saltycrane/typescript-cheatsheet) for a nice autogenerated complete reference.\n\n## `@types/react`\n\n[Link to `.d.ts`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts)\n\n**Namespace: React**\n\nMost Commonly Used Interfaces and Types\n\n- `ReactNode` - anything that is renderable _inside_ of JSX, this is NOT the same as what can be rendered by a component!\n- `Component` - base class of all class-based components\n- `PureComponent` - base class for all class-based optimized components\n- `FC`, `FunctionComponent` - a complete interface for function components, often used to type external components instead of typing your own\n- `CSSProperties` - used to type style objects\n- all events: used to type event handlers\n- all event handlers: used to type event handlers\n- all consts: `Children`, `Fragment`, ... are all public and reflect the React runtime namespace\n\nNot Commonly Used but Good to know\n\n- `Ref` - used to type `innerRef`\n- `ElementType` - used for higher order components or operations on components, e.g. [Polymorphic Components](https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase#polymorphic-components)\n- `ReactElement` - [can be used if you want to pass it to `cloneElement`](https://www.reddit.com/r/reactjs/comments/ia8sdi/any_other_typescript_users_constantly_confused/g1npahe/) aka it's pretty rarely used\n- `ComponentType` - used for higher order components where you don't specifically deal with the intrinsic components\n- `ReactPortal` - used if you specifically need to type a prop as a portal, otherwise it is part of `ReactNode`\n- `ComponentClass` - a complete interface for the produced constructor function of a class declaration that extends `Component`, often used to type external components instead of typing your own\n- `JSXElementConstructor` - anything that TypeScript considers to be a valid thing that can go into the opening tag of a JSX expression\n- `ComponentProps` - props of a component - most useful for [Wrapping/Mirroring a HTML Element](https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase#wrappingmirroring-a-html-element)\n- `ComponentPropsWithRef` - props of a component where if it is a class-based component it will replace the `ref` prop with its own instance type\n- `ComponentPropsWithoutRef` - props of a component without its `ref` prop\n- `HTMLProps` and `HTMLAttributes` - these are the most generic versions, for global attributes (see a list of [attributes marked as \"global attribute\" on MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes)). In general, prefer `React.ComponentProps`, `React.JSX.IntrinsicElements`, or [specialized HTMLAttributes interfaces](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a2aa0406e7bf269eef01292fcb2b24dee89a7d2b/types/react/index.d.ts#L1914-L2625):\n\n<details>\n  <summary>\n  List of specialized HTMLAttributes\n  </summary>\n\nNote that there are about 50 of these, which means there are some HTML elements which are not covered.\n\n- `AnchorHTMLAttributes`\n- `AudioHTMLAttributes`\n- `AreaHTMLAttributes`\n- `BaseHTMLAttributes`\n- `BlockquoteHTMLAttributes`\n- `ButtonHTMLAttributes`\n- `CanvasHTMLAttributes`\n- `ColHTMLAttributes`\n- `ColgroupHTMLAttributes`\n- `DataHTMLAttributes`\n- `DetailsHTMLAttributes`\n- `DelHTMLAttributes`\n- `DialogHTMLAttributes`\n- `EmbedHTMLAttributes`\n- `FieldsetHTMLAttributes`\n- `FormHTMLAttributes`\n- `HtmlHTMLAttributes`\n- `IframeHTMLAttributes`\n- `ImgHTMLAttributes`\n- `InsHTMLAttributes`\n- `InputHTMLAttributes`\n- `KeygenHTMLAttributes`\n- `LabelHTMLAttributes`\n- `LiHTMLAttributes`\n- `LinkHTMLAttributes`\n- `MapHTMLAttributes`\n- `MenuHTMLAttributes`\n- `MediaHTMLAttributes`\n- `MetaHTMLAttributes`\n- `MeterHTMLAttributes`\n- `QuoteHTMLAttributes`\n- `ObjectHTMLAttributes`\n- `OlHTMLAttributes`\n- `OptgroupHTMLAttributes`\n- `OptionHTMLAttributes`\n- `OutputHTMLAttributes`\n- `ParamHTMLAttributes`\n- `ProgressHTMLAttributes`\n- `SlotHTMLAttributes`\n- `ScriptHTMLAttributes`\n- `SelectHTMLAttributes`\n- `SourceHTMLAttributes`\n- `StyleHTMLAttributes`\n- `TableHTMLAttributes`\n- `TextareaHTMLAttributes`\n- `TdHTMLAttributes`\n- `ThHTMLAttributes`\n- `TimeHTMLAttributes`\n- `TrackHTMLAttributes`\n- `VideoHTMLAttributes`\n- `WebViewHTMLAttributes`\n\n</details>\n\n- all methods: `createElement`, `cloneElement`, ... are all public and reflect the React runtime API\n\n[@Ferdaber's note](https://github.com/typescript-cheatsheets/react/pull/69): I discourage the use of most `...Element` types because of how black-boxy `React.JSX.Element` is. You should almost always assume that anything produced by `React.createElement` is the base type `React.ReactElement`.\n\n**Namespace: JSX**\n\n- `Element` - the type of any JSX expression. You should ideally never need to see or use this, but you do because of [a limitation of TypeScript](https://github.com/microsoft/TypeScript/issues/21699).\n- `LibraryManagedAttributes` - It specifies other places where JSX elements can declare and initialize property types. Used to resolve static `defaultProps` and `propTypes` with the internal props type of a component.\n- `IntrinsicElements` - every possible built-in component that can be typed in as a lowercase tag name in JSX. If you're using this to get the attributes for a HTML element, `React.ComponentProps<element>` may be more readable as it doesn't require knowing what \"Intrinsic\" means.\n\nNot commonly used but good to know\n\n- `IntrinsicAttributes` set of attributes that all `IntrinsicElements` support... basically just `key`.\n- `ElementChildrenAttribute` name of property that TS looks at to figure out what types of children a component supports. Basically the `children` property\n- `ElementAttributesProperty` name of property that TS looks at to figure out what attributes a component supports. Basically the `props` property (for a class instance)\n\n**Don't use/Internal/Deprecated**\n\nAnything not listed above is considered an internal type and not public. If you're not sure you can check out the source of `@types/react`. The types are annotated accordingly.\n\n- `SFCElement`\n- `SFC`\n- `ComponentState`\n- `LegacyRef`\n- `StatelessComponent`\n- `ReactType`\n\n### Adding non-standard attributes\n\nThe attributes allowed on host components such as `button` or `img` follow the\n[HTML living standard](https://html.spec.whatwg.org/). New features that are not yet part of the living standard\nor are only implemented by certain browsers will therefore cause a type error. If\nyou specifically write code for these browsers or polyfill these attributes you can\nuse [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation) to still get those components type checked without having\nto use `any` or `@ts-ignore`.\n\nIn this example we'll add the [`loading`](https://www.chromestatus.com/feature/5645767347798016) attribute which adds support for [lazy-loading](https://web.dev/native-lazy-loading) images on Chrome:\n\n```ts\n// react-unstable-attributes.d.ts\nimport \"react\";\n\ndeclare module \"react\" {\n  interface ImgHTMLAttributes<T> extends HTMLAttributes<T> {\n    loading?: \"auto\" | \"eager\" | \"lazy\";\n  }\n}\n```\n\n## `@types/react-dom`\n\nTo be written\n"
  },
  {
    "path": "docs/advanced/utility-types.md",
    "content": "---\nid: utility_types\ntitle: \"Utility Types\"\nsidebar_label: Utility Types\n---\n\nWe will assume knowledge of utility types covered in the sister project [`typescript-cheatsheets/utilities`](https://github.com/typescript-cheatsheets/utilities). Look up libraries included there as well for your typing needs.\n\nIf you intend to maintain a large TS codebase/a nontrivial React+TS library, **we strongly recommend exploring these utilities** so that you don't reinvent the wheel and/or lose sanity trying to do so. Studying their code can also teach you a lot of advanced TS that is not covered here.\n\nI also recommend having a good working knowledge of how to construct the inbuilt utility types from scratch. See [Dr. Rauschmayer's guide](https://2ality.com/2020/06/computing-with-types.html) for a concise introduction.\n\nA level of comfort with **generic types** is therefore required. Here are some helpful resources:\n\n- https://ts.chibicode.com/generics/\n"
  },
  {
    "path": "docs/basic/editor-integration.md",
    "content": "---\nid: editor_integration\ntitle: Editor Tooling and Integration\n---\n\n- VSCode\n  - swyx's VSCode Extension: https://github.com/sw-yx/swyx-react-typescript-snippets\n  - amVim: https://marketplace.visualstudio.com/items?itemName=auiworks.amvim\n- VIM\n  - https://github.com/Quramy/tsuquyomi\n  - nvim-typescript?\n  - https://github.com/leafgarland/typescript-vim\n  - peitalin/vim-jsx-typescript\n  - NeoVim: https://github.com/neoclide/coc.nvim\n  - other discussion: https://mobile.twitter.com/ryanflorence/status/1085715595994095620\n\nYou are free to use this repo's TSX logo if you wish:\n\n[![https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png](https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png)](https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png)\n\nYou may also wish to use alternative logos - [jsx-tsx-logos](https://github.com/Protectator/jsx-tsx-logos)\n\n![https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png](https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png)\n"
  },
  {
    "path": "docs/basic/examples.md",
    "content": "---\nid: examples\ntitle: Example App\nsidebar_label: Examples\n---\n\n- [Create React App TypeScript Todo Example 2021](https://github.com/laststance/create-react-app-typescript-todo-example-2021)\n- [Ben Awad's 14 hour Fullstack React/GraphQL/TypeScript Tutorial](https://www.youtube.com/watch?v=I6ypD7qv3Z8)\n- [Cypress Realworld App](https://github.com/cypress-io/cypress-realworld-app)\n"
  },
  {
    "path": "docs/basic/getting-started/basic-type-examples.md",
    "content": "---\nid: basic_type_example\ntitle: Typing Component Props\n---\n\nThis is intended as a basic orientation and reference for React developers familiarizing with TypeScript.\n\n## Basic Prop Types Examples\n\nA list of TypeScript types you will likely use in a React+TypeScript app:\n\n```tsx\ntype AppProps = {\n  message: string;\n  count: number;\n  disabled: boolean;\n  /** array of a type! */\n  names: string[];\n  /** string literals to specify exact string values, with a union type to join them together */\n  status: \"waiting\" | \"success\";\n  /** an object with known properties (but could have more at runtime) */\n  obj: {\n    id: string;\n    title: string;\n  };\n  /** array of objects! (common) */\n  objArr: {\n    id: string;\n    title: string;\n  }[];\n  /** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */\n  obj2: object;\n  /** an interface with no required properties - (NOT COMMON, except for things like `React.Component<{}, State>`) */\n  obj3: {};\n  /** a dict object with any number of properties of the same type */\n  dict1: {\n    [key: string]: MyTypeHere;\n  };\n  dict2: Record<string, MyTypeHere>; // equivalent to dict1\n  /** function that doesn't take or return anything (VERY COMMON) */\n  onClick: () => void;\n  /** function with named prop (VERY COMMON) */\n  onChange: (id: number) => void;\n  /** function type syntax that takes an event (VERY COMMON) */\n  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;\n  /** alternative function type syntax that takes an event (VERY COMMON) */\n  onClick(event: React.MouseEvent<HTMLButtonElement>): void;\n  /** any function as long as you don't invoke it (not recommended) */\n  onSomething: Function;\n  /** an optional prop (VERY COMMON!) */\n  optional?: OptionalType;\n  /** when passing down the state setter function returned by `useState` to a child component. `number` is an example, swap out with whatever the type of your state */\n  setState: React.Dispatch<React.SetStateAction<number>>;\n};\n```\n\n### `object` as the non-primitive type\n\n`object` is a common source of misunderstanding in TypeScript. It does not mean \"any object\" but rather \"any non-primitive type\", which means it represents anything that is not `number`, `bigint`, `string`, `boolean`, `symbol`, `null` or `undefined`.\n\nTyping \"any non-primitive value\" is most likely not something that you should do much in React, which means you will probably not use `object` much.\n\n### Empty interface, `{}` and `Object`\n\nAn empty interface, `{}` and `Object` all represent \"any non-nullish value\"—not \"an empty object\" as you might think. [Using these types is a common source of misunderstanding and is not recommended](https://typescript-eslint.io/rules/no-empty-interface/).\n\n```ts\ninterface AnyNonNullishValue {} // equivalent to `type AnyNonNullishValue = {}` or `type AnyNonNullishValue = Object`\n\nlet value: AnyNonNullishValue;\n\n// these are all fine, but might not be expected\nvalue = 1;\nvalue = \"foo\";\nvalue = () => alert(\"foo\");\nvalue = {};\nvalue = { foo: \"bar\" };\n\n// these are errors\nvalue = undefined;\nvalue = null;\n```\n\n## Useful React Prop Type Examples\n\nRelevant for components that accept other React components as props.\n\n```tsx\nexport declare interface AppProps {\n  children?: React.ReactNode; // best, accepts everything React can render\n  childrenElement: React.JSX.Element; // A single React element\n  style?: React.CSSProperties; // to pass through style props\n  onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target\n  //  more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring\n  props: Props & React.ComponentPropsWithoutRef<\"button\">; // to impersonate all the props of a button element and explicitly not forwarding its ref\n  props2: Props & React.ComponentPropsWithRef<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref\n}\n```\n\n<details>\n<summary><b>Small <code>React.ReactNode</code> edge case before React 18</b></summary>\n\nBefore the [React 18 type updates](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210), this code typechecked but had a runtime error:\n\n```tsx\ntype Props = {\n  children?: React.ReactNode;\n};\n\nfunction Comp({ children }: Props) {\n  return <div>{children}</div>;\n}\nfunction App() {\n  // Before React 18: Runtime error \"Objects are not valid as a React child\"\n  // After React 18: Typecheck error \"Type '{}' is not assignable to type 'ReactNode'\"\n  return <Comp>{{}}</Comp>;\n}\n```\n\nThis is because `ReactNode` includes `ReactFragment` which allowed type `{}` before React 18.\n\n[Thanks @pomle for raising this.](https://github.com/typescript-cheatsheets/react/issues/357)\n\n</details>\n\n<details>\n <summary><b>React.JSX.Element vs React.ReactNode?</b></summary>\n\nQuote [@ferdaber](https://github.com/typescript-cheatsheets/react/issues/57): A more technical explanation is that a valid React node is not the same thing as what is returned by `React.createElement`. Regardless of what a component ends up rendering, `React.createElement` always returns an object, which is the `React.JSX.Element` interface, but `React.ReactNode` is the set of all possible return values of a component.\n\n- `React.JSX.Element` -> Return value of `React.createElement`\n- `React.ReactNode` -> Return value of a component\n\n</details>\n\n[More discussion: Where ReactNode does not overlap with React.JSX.Element](https://github.com/typescript-cheatsheets/react/issues/129)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n## Types or Interfaces?\n\nYou can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use?\n\n### TL;DR\n\nUse Interface until You Need Type - [orta](https://twitter.com/orta/status/1356129195835973632?s=20).\n\n### More Advice\n\nHere's a helpful rule of thumb:\n\n- always use `interface` for public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via _declaration merging_ if some definitions are missing.\n\n- consider using `type` for your React Component Props and State, for consistency and because it is more constrained.\n\nYou can read more about the reasoning behind this rule of thumb in [Interface vs Type alias in TypeScript 2.7](https://medium.com/@martin_hotell/interface-vs-type-alias-in-typescript-2-7-2a8f1777af4c).\n\nThe TypeScript Handbook now also includes guidance on [Differences Between Type Aliases and Interfaces](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces).\n\n> Note: At scale, there are performance reasons to prefer interfaces ([see official Microsoft notes on this](https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections)) but [take this with a grain of salt](https://news.ycombinator.com/item?id=25201887)\n\nTypes are useful for union types (e.g. `type MyType = TypeA | TypeB`) whereas Interfaces are better for declaring dictionary shapes and then `implementing` or `extending` them.\n\n### Useful table for Types vs Interfaces\n\nIt's a nuanced topic, don't get too hung up on it. Here's a handy table:\n\n| Aspect                                          | Type | Interface |\n| ----------------------------------------------- | :--: | :-------: |\n| Can describe functions                          |  ✅  |    ✅     |\n| Can describe constructors                       |  ✅  |    ✅     |\n| Can describe tuples                             |  ✅  |    ✅     |\n| Interfaces can extend it                        |  ⚠️  |    ✅     |\n| Classes can extend it                           |  🚫  |    ✅     |\n| Classes can implement it (`implements`)         |  ⚠️  |    ✅     |\n| Can intersect another one of its kind           |  ✅  |    ⚠️     |\n| Can create a union with another one of its kind |  ✅  |    🚫     |\n| Can be used to create mapped types              |  ✅  |    🚫     |\n| Can be mapped over with mapped types            |  ✅  |    ✅     |\n| Expands in error messages and logs              |  ✅  |    🚫     |\n| Can be augmented                                |  🚫  |    ✅     |\n| Can be recursive                                |  ⚠️  |    ✅     |\n\n⚠️ In some cases\n\n(source: [Karol Majewski](https://twitter.com/karoljmajewski/status/1082413696075382785))\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n"
  },
  {
    "path": "docs/basic/getting-started/class-components.md",
    "content": "---\nid: class_components\ntitle: Class Components\n---\n\nWithin TypeScript, `React.Component` is a generic type (aka `React.Component<PropType, StateType>`), so you want to provide it with (optional) prop and state type parameters:\n\n```tsx\ntype MyProps = {\n  // using `interface` is also ok\n  message: string;\n};\ntype MyState = {\n  count: number; // like this\n};\nclass App extends React.Component<MyProps, MyState> {\n  state: MyState = {\n    // optional second annotation for better type inference\n    count: 0,\n  };\n  render() {\n    return (\n      <div>\n        {this.props.message} {this.state.count}\n      </div>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgFlqAFHMAZzgF44BvCuHAD0QuAFd2wAHYBzOAANpMJFEzok8uME4oANuwhwIAawFwQSduxQykALjjsYUaTIDcFAL4fyNOo2oAZRgUZW4+MzQIMSkYBykxEAAjFTdhUV1gY3oYAAttLx80XRQrOABBMDA4JAAPZSkAE05kdBgAOgBhXEgpJFiAHiZWCA4AGgDg0KQAPgjyQSdphyYpsJ5+BcF0ozAYYAgpPUckKKa4FCkpCBD9w7hMaDgUmGUoOD96aUwVfrQkMyCKIxOJwAAMZm8ZiITRUAAoAJTzbZwIgwMRQKRwOGA7YDRrAABuM1xKN4eW07TAbHY7QsVhsSE8fAptKWynawNinlJcAGQgJxNxCJ8gh55E8QA)\n\nDon't forget that you can export/import/extend these types/interfaces for reuse.\n\n<details>\n<summary><b>Why annotate <code>state</code> twice?</b></summary>\n\nIt isn't strictly necessary to annotate the `state` class property, but it allows better type inference when accessing `this.state` and also initializing the state.\n\nThis is because they work in two different ways, the 2nd generic type parameter will allow `this.setState()` to work correctly, because that method comes from the base class, but initializing `state` inside the component overrides the base implementation so you have to make sure that you tell the compiler that you're not actually doing anything different.\n\n[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57).\n\n</details>\n\n<details>\n  <summary><b>No need for <code>readonly</code></b></summary>\n\nYou often see sample code include `readonly` to mark props and state immutable:\n\n```tsx\ntype MyProps = {\n  readonly message: string;\n};\ntype MyState = {\n  readonly count: number;\n};\n```\n\nThis is not necessary as `React.Component<P,S>` already marks them as immutable. ([See PR and discussion!](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813))\n\n</details>\n\n**Class Methods**: Do it like normal, but just remember any arguments for your functions also need to be typed:\n\n```tsx\nclass App extends React.Component<{ message: string }, { count: number }> {\n  state = { count: 0 };\n  render() {\n    return (\n      <div onClick={() => this.increment(1)}>\n        {this.props.message} {this.state.count}\n      </div>\n    );\n  }\n  increment = (amt: number) => {\n    // like this\n    this.setState((state) => ({\n      count: state.count + amt,\n    }));\n  };\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN5wQSBigDmSAFxw6MKMB5q4AXwA0cRWggBXHjG09rIAEZIoJgHwWKcHTBTccAC8FnBWtvZwAAwmANw+cET8bgAUAJTe5L6+RDDWUDxwKQnZcLJ8wABucBA8YtTAaADWQfLpwV4wABbAdCIGaETKdikAjGnGHiWlFt29ImA4YH3KqhrGsz19ugFIIuF2xtO+sgD0FZVTWdlp8ddH1wNDMsFFKCCRji5uGUFe8tNTqc4A0mkg4HM6NNISI6EgYABlfzcFI7QJ-IoA66lA6RNF7XFwADUcHeMGmxjStwSxjuxiAA)\n\n**Class Properties**: If you need to declare class properties for later use, just declare it like `state`, but without assignment:\n\n```tsx\nclass App extends React.Component<{\n  message: string;\n}> {\n  pointer: number; // like this\n  componentDidMount() {\n    this.pointer = 3;\n  }\n  render() {\n    return (\n      <div>\n        {this.props.message} and {this.pointer}\n      </div>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN4U4cEEgYoA5kgBccOjCjAeGgNwUAvgD44i8sshHuUXTwCuIAEZIoJuAHo-OGpgAGskOBgAC2A6JTg0SQhpHhgAEWA+AFkIVxSACgBKGzjlKJiRBxTvOABeOABmMzs4cziifm9C4ublIhhXKB44PJLlOFk+YAA3S1GxmzK6CpwwJdV1LXM4FH4F6KXKp1aesdk-SZnRgqblY-MgA)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n## Typing getDerivedStateFromProps\n\nBefore you start using `getDerivedStateFromProps`, please go through the [documentation](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [You Probably Don't Need Derived State](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). Derived State can be implemented using hooks which can also help set up memoization.\n\nHere are a few ways in which you can annotate `getDerivedStateFromProps`\n\n1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it.\n\n```tsx\nclass Comp extends React.Component<Props, State> {\n  static getDerivedStateFromProps(\n    props: Props,\n    state: State\n  ): Partial<State> | null {\n    //\n  }\n}\n```\n\n2. When you want the function's return value to determine your state.\n\n```tsx\nclass Comp extends React.Component<\n  Props,\n  ReturnType<typeof Comp[\"getDerivedStateFromProps\"]>\n> {\n  static getDerivedStateFromProps(props: Props) {}\n}\n```\n\n3. When you want derived state with other state fields and memoization\n\n```tsx\ntype CustomValue = any;\ninterface Props {\n  propA: CustomValue;\n}\ninterface DefinedState {\n  otherStateField: string;\n}\ntype State = DefinedState & ReturnType<typeof transformPropsToState>;\nfunction transformPropsToState(props: Props) {\n  return {\n    savedPropA: props.propA, // save for memoization\n    derivedState: props.propA,\n  };\n}\nclass Comp extends React.PureComponent<Props, State> {\n  constructor(props: Props) {\n    super(props);\n    this.state = {\n      otherStateField: \"123\",\n      ...transformPropsToState(props),\n    };\n  }\n  static getDerivedStateFromProps(props: Props, state: State) {\n    if (isEqual(props.propA, state.savedPropA)) return null;\n    return transformPropsToState(props);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOYAZwFEBHAVxQBs5tcD2IATFHQAWAOnpJWHMuQowAnmCRwAwizoxcANQ4tlAXjgoAdvIDcFYMZhIomdMoAKOMHTgBvCnDhgXAQQAuVXVNEB12PQtyAF9La1t7NGUAESRMKyR+AGUYFBsPLzgIGGFbHLykADFgJHZ+II0oKwBzKNjyBSU4cvzDVPTjTJ7lADJEJBgWKGMAFUUkAB5OpAhMOBgoEzpMaBBnCFcZiGGAPijMFmMMYAhjdc3jbd39w+PcmwAKXwO6IJe6ACUBXI3iIk2mwO83joKAAbpkXoEfC46KJvmA-AAaOAAehxcBh8K40DgICQIAgwAAXnkbsZCt5+LZgPDsu8kEF0aj0X5CtE2hQ0OwhG4VLgwHAkAAPGzGfhuZDoGCiRxTJBi8C3JDWBb-bGnSFwNC3RosDDQL4ov4ooGeEFQugsJRQS0-AFRKHrYT0UQaCpwQx2z3eYqlKDDaq1epwABEAEYAEwAZhjmIZUNEmY2Wx2UD2KKOw1drgB6f5fMKfpgwDQcGaE1STVZEZw+Z+xd+cD1BPZQWGtvTwDWH3ozDY7A7aP82KrSF9cIR-gBQLBUzuxhY7HYHqhq4h2ceubbryLXPdFZiQA)\n"
  },
  {
    "path": "docs/basic/getting-started/concurrent.md",
    "content": "---\nid: concurrent\ntitle: Concurrent React/React Suspense\n---\n\n_Not written yet._ watch <https://github.com/sw-yx/fresh-async-react> for more on React Suspense and Time Slicing.\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n"
  },
  {
    "path": "docs/basic/getting-started/context.md",
    "content": "---\nid: context\ntitle: Context\n---\n\n## Basic example\n\nHere's a basic example of creating a context containing the active theme.\n\n```tsx\nimport { createContext } from \"react\";\n\ntype ThemeContextType = \"light\" | \"dark\";\n\nconst ThemeContext = createContext<ThemeContextType>(\"light\");\n```\n\nWrap the components that need the context with a context provider:\n\n```tsx\nimport { useState } from \"react\";\n\nconst App = () => {\n  const [theme, setTheme] = useState<ThemeContextType>(\"light\");\n\n  return (\n    <ThemeContext.Provider value={theme}>\n      <MyComponent />\n    </ThemeContext.Provider>\n  );\n};\n```\n\nCall `useContext` to read and subscribe to the context.\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const theme = useContext(ThemeContext);\n\n  return <p>The current theme is {theme}.</p>;\n};\n```\n\n## Without default context value\n\nIf you don't have any meaningful default value, specify `null`:\n\n```tsx\nimport { createContext } from \"react\";\n\ninterface CurrentUserContextType {\n  username: string;\n}\n\nconst CurrentUserContext = createContext<CurrentUserContextType | null>(null);\n```\n\n```tsx\nconst App = () => {\n  const [currentUser, setCurrentUser] = useState<CurrentUserContextType>({\n    username: \"filiptammergard\",\n  });\n\n  return (\n    <CurrentUserContext.Provider value={currentUser}>\n      <MyComponent />\n    </CurrentUserContext.Provider>\n  );\n};\n```\n\nNow that the type of the context can be `null`, you'll notice that you'll get a `'currentUser' is possibly 'null'` TypeScript error if you try to access the `username` property. You can use optional chaining to access `username`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const currentUser = useContext(CurrentUserContext);\n\n  return <p>Name: {currentUser?.username}.</p>;\n};\n```\n\nHowever, it would be preferable to not have to check for `null`, since we know that the context won't be `null`. One way to do that is to provide a custom hook to use the context, where an error is thrown if the context is not provided:\n\n```tsx\nimport { createContext } from \"react\";\n\ninterface CurrentUserContextType {\n  username: string;\n}\n\nconst CurrentUserContext = createContext<CurrentUserContextType | null>(null);\n\nconst useCurrentUser = () => {\n  const currentUserContext = useContext(CurrentUserContext);\n\n  if (!currentUserContext) {\n    throw new Error(\n      \"useCurrentUser has to be used within <CurrentUserContext.Provider>\"\n    );\n  }\n\n  return currentUserContext;\n};\n```\n\nUsing a runtime type check in this will has the benefit of printing a clear error message in the console when a provider is not wrapping the components properly. Now it's possible to access `currentUser.username` without checking for `null`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const currentUser = useCurrentUser();\n\n  return <p>Username: {currentUser.username}.</p>;\n};\n```\n\n### Type assertion as an alternative\n\nAnother way to avoid having to check for `null` is to use type assertion to tell TypeScript you know the context is not `null`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () => {\n  const currentUser = useContext(CurrentUserContext);\n\n  return <p>Name: {currentUser!.username}.</p>;\n};\n```\n\nAnother option is to use an empty object as default value and cast it to the expected context type:\n\n```tsx\nconst CurrentUserContext = createContext<CurrentUserContextType>(\n  {} as CurrentUserContextType\n);\n```\n\nYou can also use non-null assertion to get the same result:\n\n```tsx\nconst CurrentUserContext = createContext<CurrentUserContextType>(null!);\n```\n\nWhen you don't know what to choose, prefer runtime checking and throwing over type asserting.\n"
  },
  {
    "path": "docs/basic/getting-started/default-props.md",
    "content": "---\nid: default_props\ntitle: Typing defaultProps\n---\n\n## You May Not Need `defaultProps`\n\nAs per [this tweet](https://twitter.com/dan_abramov/status/1133878326358171650), defaultProps will eventually be deprecated. You can check the discussions here:\n\n- [Original tweet](https://twitter.com/hswolff/status/1133759319571345408)\n- More info can also be found in [this article](https://medium.com/@matanbobi/react-defaultprops-is-dying-whos-the-contender-443c19d9e7f1)\n\nThe consensus is to use object default values.\n\nFunction Components:\n\n```tsx\ntype GreetProps = { age?: number };\n\nconst Greet = ({ age = 21 }: GreetProps) => // etc\n```\n\nClass Components:\n\n```tsx\ntype GreetProps = {\n  age?: number;\n};\n\nclass Greet extends React.Component<GreetProps> {\n  render() {\n    const { age = 21 } = this.props;\n    /*...*/\n  }\n}\n\nlet el = <Greet age={3} />;\n```\n\n## Typing `defaultProps`\n\nType inference improved greatly for `defaultProps` in [TypeScript 3.0+](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html), although [some edge cases are still problematic](https://github.com/typescript-cheatsheets/react/issues/61).\n\n**Function Components**\n\n```tsx\n// using typeof as a shortcut; note that it hoists!\n// you can also declare the type of DefaultProps if you choose\n// e.g. https://github.com/typescript-cheatsheets/react/issues/415#issuecomment-841223219\ntype GreetProps = { age: number } & typeof defaultProps;\n\nconst defaultProps = {\n  age: 21,\n};\n\nconst Greet = (props: GreetProps) => {\n  // etc\n};\nGreet.defaultProps = defaultProps;\n```\n\n_[See this in TS Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAOKVYwAKxY6ALxwA3igDmWAFxwAdgFcQAIyxQ4AXzgAyOM1YQCcACZYCyeQBte-VPVwRZqeCbOXrEAXGEi6cCdLgAJgBGABo6dXo6e0d4TixuLzgACjAbGXjuPg9UAEovAD5RXzhKGHkoWTgAHiNgADcCkTScgDpkSTgAeiQFZVVELvVqrrrGiPpMmFaXcytsz2FZtwXbOiA)_\n\nFor **Class components**, there are [a couple ways to do it](https://github.com/typescript-cheatsheets/react/pull/103#issuecomment-481061483) (including using the `Pick` utility type) but the recommendation is to \"reverse\" the props definition:\n\n```tsx\ntype GreetProps = typeof Greet.defaultProps & {\n  age: number;\n};\n\nclass Greet extends React.Component<GreetProps> {\n  static defaultProps = {\n    age: 21,\n  };\n  /*...*/\n}\n\n// Type-checks! No type assertions needed!\nlet el = <Greet age={3} />;\n```\n\n<details>\n<summary><b><code>React.JSX.LibraryManagedAttributes</code> nuance for library authors</b></summary>\n\nThe above implementations work fine for App creators, but sometimes you want to be able to export `GreetProps` so that others can consume it. The problem here is that the way `GreetProps` is defined, `age` is a required prop when it isn't because of `defaultProps`.\n\nThe insight to have here is that [`GreetProps` is the _internal_ contract for your component, not the _external_, consumer facing contract](https://github.com/typescript-cheatsheets/react/issues/66#issuecomment-453878710). You could create a separate type specifically for export, or you could make use of the `React.JSX.LibraryManagedAttributes` utility:\n\n```tsx\n// internal contract, should not be exported out\ntype GreetProps = {\n  age: number;\n};\n\nclass Greet extends Component<GreetProps> {\n  static defaultProps = { age: 21 };\n}\n\n// external contract\nexport type ApparentGreetProps = React.JSX.LibraryManagedAttributes<\n  typeof Greet,\n  GreetProps\n>;\n```\n\nThis will work properly, although hovering over`ApparentGreetProps`may be a little intimidating. You can reduce this boilerplate with the`ComponentProps` utility detailed below.\n\n</details>\n\n## Consuming Props of a Component with defaultProps\n\nA component with `defaultProps` may seem to have some required props that actually aren't.\n\n### Problem Statement\n\nHere's what you want to do:\n\n```tsx\ninterface IProps {\n  name: string;\n}\nconst defaultProps = {\n  age: 25,\n};\nconst GreetComponent = ({ name, age }: IProps & typeof defaultProps) => (\n  <div>{`Hello, my name is ${name}, ${age}`}</div>\n);\nGreetComponent.defaultProps = defaultProps;\n\nconst TestComponent = (props: React.ComponentProps<typeof GreetComponent>) => {\n  return <h1 />;\n};\n\n// Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'\nconst el = <TestComponent name=\"foo\" />;\n```\n\n### Solution\n\nDefine a utility that applies `React.JSX.LibraryManagedAttributes`:\n\n```tsx\ntype ComponentProps<T> = T extends\n  | React.ComponentType<infer P>\n  | React.Component<infer P>\n  ? React.JSX.LibraryManagedAttributes<T, P>\n  : never;\n\nconst TestComponent = (props: ComponentProps<typeof GreetComponent>) => {\n  return <h1 />;\n};\n\n// No error\nconst el = <TestComponent name=\"foo\" />;\n```\n\n[_See this in TS Playground_](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAMImQB2W3MABWJhUAHgAqAPjgBeOOLhYAHjD4ATdNjwwAdJ3ARe-cSyyjg3AlihwB0gD6Yqu-Tz4xzl67cl04cAH44ACkAZQANHQAZYAAjKGQoJgBZZG5kAHMsNQBBGBgoOIBXVTFxABofPzgALjheADdrejoLVSgCPDYASSEIETgAb2r0kCw61AKLDPoAXzpcQ0m4NSxOooAbQWF0OWH-TPG4ACYAVnK6WfpF7mWAcUosGFdDd1k4AApB+uQxysO4LM6r0dnAAGRwZisCAEFZrZCbbb9VAASlk0g+1VEamADUkgwABgAJLAbDYQSogJg-MZwYDoAAkg1GWFmlSZh1mBNmogA9Di8XQUfQHlgni8jLpVustn0BnJpQjZTsWrzeXANsh2gwbstxFhJhK3nIPmAdnUjfw5WIoVgYXBReKuK9+JI0TJpPs4JQYEUoNw4KIABYARjgvN8VwYargADkIIooMQoAslvBSe8JAbns7JTSsDIyAQIBAyOHJDQgA)\n\n## Misc Discussions and Knowledge\n\n<details>\n<summary><b>Why does <code>React.FC</code> break <code>defaultProps</code>?</b></summary>\n\nYou can check the discussions here:\n\n- https://medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680\n- https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30695\n- https://github.com/typescript-cheatsheets/react/issues/87\n\nThis is just the current state and may be fixed in future.\n\n</details>\n\n<details>\n<summary><b>TypeScript 2.9 and earlier</b></summary>\n\nFor TypeScript 2.9 and earlier, there's more than one way to do it, but this is the best advice we've yet seen:\n\n```ts\ntype Props = Required<typeof MyComponent.defaultProps> & {\n  /* additional props here */\n};\n\nexport class MyComponent extends React.Component<Props> {\n  static defaultProps = {\n    foo: \"foo\",\n  };\n}\n```\n\nOur former recommendation used the `Partial type` feature in TypeScript, which means that the current interface will fulfill a partial version on the wrapped interface. In that way we can extend defaultProps without any changes in the types!\n\n```ts\ninterface IMyComponentProps {\n  firstProp?: string;\n  secondProp: IPerson[];\n}\n\nexport class MyComponent extends React.Component<IMyComponentProps> {\n  public static defaultProps: Partial<IMyComponentProps> = {\n    firstProp: \"default\",\n  };\n}\n```\n\nThe problem with this approach is it causes complex issues with the type inference working with `React.JSX.LibraryManagedAttributes`. Basically it causes the compiler to think that when creating a JSX expression with that component, that all of its props are optional.\n\n[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57) and [here](https://github.com/typescript-cheatsheets/react/issues/61).\n\n</details>\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n"
  },
  {
    "path": "docs/basic/getting-started/error-boundaries.md",
    "content": "---\nid: error_boundaries\ntitle: Error Boundaries\n---\n\n### Option 1: Using react-error-boundary\n\n[React-error-boundary](https://github.com/bvaughn/react-error-boundary) - is a lightweight package ready to use for this scenario with TS support built-in.\nThis approach also lets you avoid class components that are not that popular anymore.\n\n### Option 2: Writing your custom error boundary component\n\nIf you don't want to add a new npm package for this, you can also write your own `ErrorBoundary` component.\n\n```jsx\nimport React, { Component, ErrorInfo, ReactNode } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n}\n\ninterface State {\n  hasError: boolean;\n}\n\nclass ErrorBoundary extends Component<Props, State> {\n  public state: State = {\n    hasError: false\n  };\n\n  public static getDerivedStateFromError(_: Error): State {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true };\n  }\n\n  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n    console.error(\"Uncaught error:\", error, errorInfo);\n  }\n\n  public render() {\n    if (this.state.hasError) {\n      return <h1>Sorry.. there was an error</h1>;\n    }\n\n    return this.props.children;\n  }\n}\n\nexport default ErrorBoundary;\n\n```\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n"
  },
  {
    "path": "docs/basic/getting-started/forms-and-events.md",
    "content": "---\nid: forms_and_events\ntitle: Forms and Events\n---\n\nIf performance is not an issue (and it usually isn't!), inlining handlers is easiest as you can just use [type inference and contextual typing](https://www.typescriptlang.org/docs/handbook/type-inference.html#contextual-typing):\n\n```tsx\nconst el = (\n  <button\n    onClick={(event) => {\n      /* event will be correctly typed automatically! */\n    }}\n  />\n);\n```\n\nBut if you need to define your event handler separately, IDE tooling really comes in handy here, as the @type definitions come with a wealth of typing. Type what you are looking for and usually the autocomplete will help you out. Here is what it looks like for an `onChange` for a form event:\n\n```tsx\ntype State = {\n  text: string;\n};\nclass App extends React.Component<Props, State> {\n  state = {\n    text: \"\",\n  };\n\n  // typing on RIGHT hand side of =\n  onChange = (e: React.FormEvent<HTMLInputElement>): void => {\n    this.setState({ text: e.currentTarget.value });\n  };\n  render() {\n    return (\n      <div>\n        <input type=\"text\" value={this.state.text} onChange={this.onChange} />\n      </div>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2KA9Drg8IcMDjB1tcblwBccOjCjAeAcwDcmlRQB8W8ovso3HAAvL6KilYwtgBE0R7ulH5wepYAnmBOznAQPIgAkgDiABIAKnAAFij8dsB8SNmYIZo5YpUu9aEAFEi2QhgiAGLQIACiAG4ysqUAsgAyeTxgAK4wI9RIIDJeAJS2YxC1IT5KFjDlwHQidEgwAMowgUidSpacUewiaEtQRDwwJSgoM4biIxihqEt6iptglFCpYXBfnUoJ1tmFwkQYN9cp0LIpZHxgGMvHjwrInMt4DB0khgtFItE4GCIbSlGcLlcHtwRJEVNkeK0qsDgmzzpcWm1gXydCSkuE4LIdITiRYYR4KCogA)\n\nInstead of typing the arguments and return values with `React.FormEvent<>` and `void`, you may alternatively apply types to the event handler itself (_contributed by @TomasHubelbauer_):\n\n```tsx\n  // typing on LEFT hand side of =\n  onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {\n    this.setState({text: e.currentTarget.value})\n  }\n```\n\n<details>\n\n<summary><b>Why two ways to do the same thing?</b></summary>\n\nThe first method uses an inferred method signature `(e: React.FormEvent<HTMLInputElement>): void` and the second method enforces a type of the delegate provided by `@types/react`. So `React.ChangeEventHandler<>` is simply a \"blessed\" typing by `@types/react`, whereas you can think of the inferred method as more... _artisanally hand-rolled_. Either way it's a good pattern to know. [See our Github PR for more](https://github.com/typescript-cheatsheets/react/pull/24).\n\n</details>\n\n> Starting with React v19.2.10 `FormEvent` and `FormEventHandler` are deprecated and should be replaced with `SubmitEvent` and `SubmitEventHandler`. The older event types will still work but trigger a deprecation message.\n\n**Typing onSubmit, with Uncontrolled components in a Form**\n\nIf you don't quite care about the type of the event, you can just use `React.SyntheticEvent`. If your target form has custom named inputs that you'd like to access, you can use a type assertion:\n\n```tsx\n<form\n  ref={formRef}\n  onSubmit={(e: React.SyntheticEvent) => {\n    e.preventDefault();\n    const target = e.target as typeof e.target & {\n      email: { value: string };\n      password: { value: string };\n    };\n    const email = target.email.value; // typechecks!\n    const password = target.password.value; // typechecks!\n    // etc...\n  }}\n>\n  <div>\n    <label>\n      Email:\n      <input type=\"email\" name=\"email\" />\n    </label>\n  </div>\n  <div>\n    <label>\n      Password:\n      <input type=\"password\" name=\"password\" />\n    </label>\n  </div>\n  <div>\n    <input type=\"submit\" value=\"Log in\" />\n  </div>\n</form>\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtCAOwGctoRlM4BeRYmAOgFc6kLABQBKClVoM4AMSbs4o9gD4FFOHAA8mJmrhFMbAN7aozJJgC+u2gGVeAIxDAYRoUgBcndDxsBPGjAAFkgwwGgAogBuSAEiynCGuupI3GBE0QEAIuYovAA2MKIA3Elw1PTwMChQAOYh8ilVtfUodHAwvmBIEKyN1XXwAGQJpckgKMB5noZwkSh5vB5wDFDANDVwFiXk6rtwYK10AO7QACbTs-OLnitrG1ulDzu75VJI45PyTQPc7xN53DmCyQRTgAHowe1Okg0ME0ABrOgAQlKr3gBzoxzOX36IVShxOUFOgKuIPBkI6XVhMMRKOe6ghcBCaG4rN0Fis5CUug0p2AkW59M0eRQ9iQeUFe3U4Q+U1GmjWYF4lWhbAARH9Jmq4DQUCAkOrNXltWDJbsNGCRWKJTywXyBTz7Wb1BoreLnbsAAoEs7ueUaRXKqFddUYrFE7W6-Whn0R8Eei1um3PC1Ox38hOBlUhtV0BxOGDaoGLdUAGQgGzWJrNqYzFAtJhAgpEQA)\n\nOf course, if you're making any sort of significant form, [you should use Formik](https://jaredpalmer.com/formik) or [React Hook Form](https://react-hook-form.com/), which are written in TypeScript.\n\n### List of event types\n\n| Event Type       | Description                                                                                                                                                                                                                                                            |\n| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| AnimationEvent   | CSS Animations.                                                                                                                                                                                                                                                        |\n| ChangeEvent      | Changing the value of `<input>`, `<select>` and `<textarea>` element.                                                                                                                                                                                                  |\n| ClipboardEvent   | Using copy, paste and cut events.                                                                                                                                                                                                                                      |\n| CompositionEvent | Events that occur due to the user indirectly entering text (e.g. depending on Browser and PC setup, a popup window may appear with additional characters if you e.g. want to type Japanese on a US Keyboard)                                                           |\n| DragEvent        | Drag and drop interaction with a pointer device (e.g. mouse).                                                                                                                                                                                                          |\n| FocusEvent       | Event that occurs when elements gets or loses focus.                                                                                                                                                                                                                   |\n| FormEvent        | Event that occurs whenever a form or form element gets/loses focus, a form element value is changed or the form is submitted.                                                                                                                                          |\n| InvalidEvent     | Fired when validity restrictions of an input fails (e.g `<input type=\"number\" max=\"10\">` and someone would insert number 20).                                                                                                                                          |\n| KeyboardEvent    | User interaction with the keyboard. Each event describes a single key interaction.                                                                                                                                                                                     |\n| InputEvent       | Event that occurs before the value of `<input>`, `<select>` and `<textarea>` changes.                                                                                                                                                                                  |\n| MouseEvent       | Events that occur due to the user interacting with a pointing device (e.g. mouse)                                                                                                                                                                                      |\n| PointerEvent     | Events that occur due to user interaction with a variety pointing of devices such as mouse, pen/stylus, a touchscreen and which also supports multi-touch. Unless you develop for older browsers (IE10 or Safari 12), pointer events are recommended. Extends UIEvent. |\n| TouchEvent       | Events that occur due to the user interacting with a touch device. Extends UIEvent.                                                                                                                                                                                    |\n| TransitionEvent  | CSS Transition. Not fully browser supported. Extends UIEvent                                                                                                                                                                                                           |\n| UIEvent          | Base Event for Mouse, Touch and Pointer events.                                                                                                                                                                                                                        |\n| WheelEvent       | Scrolling on a mouse wheel or similar input device. (Note: `wheel` event should not be confused with the `scroll` event)                                                                                                                                               |\n| SyntheticEvent   | The base event for all above events. Should be used when unsure about event type                                                                                                                                                                                       |\n"
  },
  {
    "path": "docs/basic/getting-started/forward-create-ref.md",
    "content": "---\nid: forward_and_create_ref\ntitle: forwardRef/createRef\n---\n\nFor `useRef`, check the [Hooks section](/docs/basic/getting-started/hooks#useref).\n\n## Ref as a Prop (Recommended for React 19+)\n\nIn React 19+, you can access `ref` directly as a prop in function components - no `forwardRef` wrapper needed.\n\n### Option 1: Inherit all props from a native element\n\nUse `ComponentPropsWithRef` to inherit all props from a native element.\n\n```tsx\nimport { ComponentPropsWithRef, useRef } from \"react\";\n\nfunction MyInput(props: ComponentPropsWithRef<\"input\">) {\n  return <input {...props} />;\n}\n\n// Usage in parent component\nfunction Parent() {\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  return <MyInput ref={inputRef} placeholder=\"Type here...\" />;\n}\n```\n\n### Option 2: Explicit typing\n\nIf you have custom props and want fine-grained control, you can explicitly type the ref:\n\n```tsx\nimport { Ref, useRef } from \"react\";\n\ninterface MyInputProps {\n  placeholder: string;\n  ref: Ref<HTMLInputElement>;\n}\n\nfunction MyInput(props: MyInputProps) {\n  return <input {...props} />;\n}\n\n// Usage in parent component\nfunction Parent() {\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  return <MyInput ref={inputRef} placeholder=\"Type here...\" />;\n}\n```\n\n**Read more**: [Wrapping/Mirroring a HTML Element](/docs/advanced/patterns_by_usecase#wrappingmirroring-a-html-element)\n\n## Legacy Approaches (Pre-React 19)\n\n### forwardRef\n\nFor React 18 and earlier, use `forwardRef`:\n\n```tsx\nimport { forwardRef, ReactNode } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n  type: \"submit\" | \"button\";\n}\nexport type Ref = HTMLButtonElement;\n\nexport const FancyButton = forwardRef<Ref, Props>((props, ref) => (\n  <button ref={ref} className=\"MyClassName\" type={props.type}>\n    {props.children}\n  </button>\n));\n```\n\n<details>\n<summary><b>Side note: the <code>ref</code> you get from <code>forwardRef</code> is mutable so you can assign to it if needed.</b></summary>\n\nThis was done [on purpose](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43265/). You can make it immutable if you have to - assign `React.Ref` if you want to ensure nobody reassigns it:\n\n```tsx\nimport { forwardRef, ReactNode, Ref } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n  type: \"submit\" | \"button\";\n}\n\nexport const FancyButton = forwardRef(\n  (\n    props: Props,\n    ref: Ref<HTMLButtonElement> // <-- explicit immutable ref type\n  ) => (\n    <button ref={ref} className=\"MyClassName\" type={props.type}>\n      {props.children}\n    </button>\n  )\n);\n```\n\n</details>\n\nIf you need to grab props from a component that forwards refs, use [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770).\n\n### createRef\n\n`createRef` is mostly used for class components. Function components typically rely on `useRef` instead.\n\n```tsx\nimport { createRef, PureComponent } from \"react\";\n\nclass CssThemeProvider extends PureComponent<Props> {\n  private rootRef = createRef<HTMLDivElement>();\n\n  render() {\n    return <div ref={this.rootRef}>{this.props.children}</div>;\n  }\n}\n```\n\n## Generic Components with Refs\n\nGeneric components typically require manual ref handling since their generic nature prevents automatic type inference. Here are the main approaches:\n\nRead more context in [this article](https://fettblog.eu/typescript-react-generic-forward-refs/).\n\n### Option 1: Wrapper Component\n\nThe most straightforward approach is to manually handle refs through props:\n\n```tsx\ninterface ClickableListProps<T> {\n  items: T[];\n  onSelect: (item: T) => void;\n  mRef?: React.Ref<HTMLUListElement> | null;\n}\n\nexport function ClickableList<T>(props: ClickableListProps<T>) {\n  return (\n    <ul ref={props.mRef}>\n      {props.items.map((item, i) => (\n        <li key={i}>\n          <button onClick={() => props.onSelect(item)}>Select</button>\n          {item}\n        </li>\n      ))}\n    </ul>\n  );\n}\n```\n\n### Option 2: Redeclare forwardRef\n\nFor true `forwardRef` behavior with generics, extend the module declaration:\n\n```tsx\n// Redeclare forwardRef to support generics\ndeclare module \"react\" {\n  function forwardRef<T, P = {}>(\n    render: (props: P, ref: React.Ref<T>) => React.ReactElement | null\n  ): (props: P & React.RefAttributes<T>) => React.ReactElement | null;\n}\n\n// Now you can use forwardRef with generics normally\nimport { forwardRef, ForwardedRef } from \"react\";\n\ninterface ClickableListProps<T> {\n  items: T[];\n  onSelect: (item: T) => void;\n}\n\nfunction ClickableListInner<T>(\n  props: ClickableListProps<T>,\n  ref: ForwardedRef<HTMLUListElement>\n) {\n  return (\n    <ul ref={ref}>\n      {props.items.map((item, i) => (\n        <li key={i}>\n          <button onClick={() => props.onSelect(item)}>Select</button>\n          {item}\n        </li>\n      ))}\n    </ul>\n  );\n}\n\nexport const ClickableList = forwardRef(ClickableListInner);\n```\n\n### Option 3: Call Signature\n\nIf you need both generic support and proper forwardRef behavior with full type inference, you can use the call signature:\n\n```tsx\n// Add to your type definitions (e.g. in `index.d.ts` file)\ninterface ForwardRefWithGenerics extends React.FC<WithForwardRefProps<Option>> {\n  <T extends Option>(props: WithForwardRefProps<T>): ReturnType<\n    React.FC<WithForwardRefProps<T>>\n  >;\n}\n\nexport const ClickableListWithForwardRef: ForwardRefWithGenerics =\n  forwardRef(ClickableList);\n```\n\nCredits: [https://stackoverflow.com/a/73795494](https://stackoverflow.com/a/73795494)\n\n:::note\nOption 1 is usually sufficient and clearer. Use Option 2 when you specifically need `forwardRef` behavior. Use Option 3 for advanced library scenarios requiring both generics and full forwardRef type inference.\n:::\n\n## Additional Resources\n\n- [React refs with TypeScript](https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315)\n- [Conditional rendering with forwardRef](https://github.com/typescript-cheatsheets/react/issues/167)\n\n---\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new)\n"
  },
  {
    "path": "docs/basic/getting-started/function-components.md",
    "content": "---\nid: function_components\ntitle: Function Components\n---\n\nThese can be written as normal functions that take a `props` argument and return a JSX element.\n\n```tsx\n// Declaring type of props - see \"Typing Component Props\" for more examples\ntype AppProps = {\n  message: string;\n}; /* use `interface` if exporting so that consumers can extend */\n\n// Easiest way to declare a Function Component; return type is inferred.\nconst App = ({ message }: AppProps) => <div>{message}</div>;\n\n// You can choose to annotate the return type so an error is raised if you accidentally return some other type\nconst App = ({ message }: AppProps): React.JSX.Element => <div>{message}</div>;\n\n// You can also inline the type declaration; eliminates naming the prop types, but looks repetitive\nconst App = ({ message }: { message: string }) => <div>{message}</div>;\n\n// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.\n// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.\nconst App: React.FunctionComponent<{ message: string }> = ({ message }) => (\n  <div>{message}</div>\n);\n// or\nconst App: React.FC<AppProps> = ({ message }) => <div>{message}</div>;\n```\n\n> Tip: You might use [Paul Shen's VS Code Extension](https://marketplace.visualstudio.com/items?itemName=paulshen.paul-typescript-toolkit) to automate the type destructure declaration (incl a [keyboard shortcut](https://twitter.com/_paulshen/status/1392915279466745857?s=20)).\n\n<details>\n\n<summary><b>Why is <code>React.FC</code> not needed? What about <code>React.FunctionComponent</code>/<code>React.VoidFunctionComponent</code>?</b></summary>\n\nYou may see this in many React+TypeScript codebases:\n\n```tsx\nconst App: React.FunctionComponent<{ message: string }> = ({ message }) => (\n  <div>{message}</div>\n);\n```\n\nHowever, the general consensus today is that `React.FunctionComponent` (or the shorthand `React.FC`) is not needed. If you're still using React 17 or TypeScript lower than 5.1, it is even [discouraged](https://github.com/facebook/create-react-app/pull/8177). This is a nuanced opinion of course, but if you agree and want to remove `React.FC` from your codebase, you can use [this jscodeshift codemod](https://github.com/gndelia/codemod-replace-react-fc-typescript).\n\nSome differences from the \"normal function\" version:\n\n- `React.FunctionComponent` is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).\n\n- It provides typechecking and autocomplete for static properties like `displayName`, `propTypes`, and `defaultProps`.\n\n  - Note that there are some known issues using `defaultProps` with `React.FunctionComponent`. See [this issue for details](https://github.com/typescript-cheatsheets/react/issues/87). We maintain a separate `defaultProps` section you can also look up.\n\n- Before the [React 18 type updates](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210), `React.FunctionComponent` provided an implicit definition of `children` (see below), which was heavily debated and is one of the reasons [`React.FC` was removed from the Create React App TypeScript template](https://github.com/facebook/create-react-app/pull/8177).\n\n```tsx\n// before React 18 types\nconst Title: React.FunctionComponent<{ title: string }> = ({\n  children,\n  title,\n}) => <div title={title}>{children}</div>;\n```\n\n<details>\n<summary>(Deprecated)<b>Using <code>React.VoidFunctionComponent</code> or <code>React.VFC</code> instead</b></summary>\n\nIn [@types/react 16.9.48](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643), the `React.VoidFunctionComponent` or `React.VFC` type was added for typing `children` explicitly.\nHowever, please be aware that `React.VFC` and `React.VoidFunctionComponent` were deprecated in React 18 (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/59882), so this interim solution is no longer necessary or recommended in React 18+.\n\nPlease use regular function components or `React.FC` instead.\n\n```ts\ntype Props = { foo: string };\n\n// OK now, in future, error\nconst FunctionComponent: React.FunctionComponent<Props> = ({\n  foo,\n  children,\n}: Props) => {\n  return (\n    <div>\n      {foo} {children}\n    </div>\n  ); // OK\n};\n\n// Error now, in future, deprecated\nconst VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({\n  foo,\n  children,\n}) => {\n  return (\n    <div>\n      {foo}\n      {children}\n    </div>\n  );\n};\n```\n\n</details>\n\n- _In the future_, it may automatically mark props as `readonly`, though that's a moot point if the props object is destructured in the parameter list.\n\nIn most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of `React.FunctionComponent`.\n\n</details>\n"
  },
  {
    "path": "docs/basic/getting-started/hooks.md",
    "content": "---\nid: hooks\ntitle: Hooks\n---\n\nHooks are [supported in `@types/react` from v16.8 up](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031).\n\n## useState\n\nType inference works very well for simple values:\n\n```tsx\nconst [state, setState] = useState(false);\n// `state` is inferred to be a boolean\n// `setState` only takes booleans\n```\n\nSee also the [Using Inferred Types](https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types/#using-inferred-types) section if you need to use a complex type that you've relied on inference for.\n\nHowever, many hooks are initialized with null-ish default values, and you may wonder how to provide types. Explicitly declare the type, and use a union type:\n\n```tsx\nconst [user, setUser] = useState<User | null>(null);\n\n// later...\nsetUser(newUser);\n```\n\nYou can also use type assertions if a state is initialized soon after setup and always has a value after:\n\n```tsx\nconst [user, setUser] = useState<User>({} as User);\n\n// later...\nsetUser(newUser);\n```\n\nThis temporarily \"lies\" to the TypeScript compiler that `{}` is of type `User`. You should follow up by setting the `user` state — if you don't, the rest of your code may rely on the fact that `user` is of type `User` and that may lead to runtime errors.\n\n## useCallback\n\nYou can type the `useCallback` just like any other function.\n\n```ts\nconst memoizedCallback = useCallback(\n  (param1: string, param2: number) => {\n    console.log(param1, param2)\n    return { ok: true }\n  },\n  [...],\n);\n/**\n * VSCode will show the following type:\n * const memoizedCallback:\n *  (param1: string, param2: number) => { ok: boolean }\n */\n```\n\nNote that for React < 18, the function signature of `useCallback` typed arguments as `any[]` by default:\n\n```ts\nfunction useCallback<T extends (...args: any[]) => any>(\n  callback: T,\n  deps: DependencyList\n): T;\n```\n\nIn React >= 18, the function signature of `useCallback` changed to the following:\n\n```ts\nfunction useCallback<T extends Function>(callback: T, deps: DependencyList): T;\n```\n\nTherefore, the following code will yield \"`Parameter 'e' implicitly has an 'any' type.`\" error in React >= 18, but not <17.\n\n```ts\n// @ts-expect-error Parameter 'e' implicitly has 'any' type.\nuseCallback((e) => {}, []);\n// Explicit 'any' type.\nuseCallback((e: any) => {}, []);\n```\n\n## useReducer\n\nYou can use [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions) for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.\n\n```tsx\nimport { useReducer } from \"react\";\n\nconst initialState = { count: 0 };\n\ntype ACTIONTYPE =\n  | { type: \"increment\"; payload: number }\n  | { type: \"decrement\"; payload: string };\n\nfunction reducer(state: typeof initialState, action: ACTIONTYPE) {\n  switch (action.type) {\n    case \"increment\":\n      return { count: state.count + action.payload };\n    case \"decrement\":\n      return { count: state.count - Number(action.payload) };\n    default:\n      throw new Error();\n  }\n}\n\nfunction Counter() {\n  const [state, dispatch] = useReducer(reducer, initialState);\n  return (\n    <>\n      Count: {state.count}\n      <button onClick={() => dispatch({ type: \"decrement\", payload: \"5\" })}>\n        -\n      </button>\n      <button onClick={() => dispatch({ type: \"increment\", payload: 5 })}>\n        +\n      </button>\n    </>\n  );\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6WfTDRSvKnMgpEIgBhxTIJwEQANZSWRjI5SdPIF1u8RXMayZ7lSphEnRWLxbFNagAVmomhF6fZqYA9OXKxxM2KQWWK1WoTW643m63pB2u+7e-3SkEQsPamOGik1FO55p08jl6vdxuKcvv8h4yAmhAA)\n\n<details>\n\n<summary><b>Usage with <code>Reducer</code> from <code>redux</code></b></summary>\n\nIn case you use the [redux](https://github.com/reduxjs/redux) library to write reducer function, It provides a convenient helper of the format `Reducer<State, Action>` which takes care of the return type for you.\n\nSo the above reducer example becomes:\n\n```tsx\nimport { Reducer } from 'redux';\n\nexport function reducer: Reducer<AppState, Action>() {}\n```\n\n</details>\n\n## useEffect / useLayoutEffect\n\nBoth of `useEffect` and `useLayoutEffect` are used for performing <b>side effects</b> and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When using `useEffect`, take care not to return anything other than a function or `undefined`, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:\n\n```ts\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(\n    () =>\n      setTimeout(() => {\n        /* do stuff */\n      }, timerMs),\n    [timerMs]\n  );\n  // bad example! setTimeout implicitly returns a number\n  // because the arrow function body isn't wrapped in curly braces\n  return null;\n}\n```\n\n<details>\n<summary><b>Solution to the above example</b></summary>\n\n```tsx\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(() => {\n    setTimeout(() => {\n      /* do stuff */\n    }, timerMs);\n  }, [timerMs]);\n  // better; use the void keyword to make sure you return undefined\n  return null;\n}\n```\n\n</details>\n\n## useRef\n\nIn TypeScript, `useRef` returns a reference that is either [read-only](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1025-L1039) or [mutable](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1012-L1023), depends on whether your type argument fully covers the initial value or not. Choose one that suits your use case.\n\n### Option 1: DOM element ref\n\n**[To access a DOM element](https://reactjs.org/docs/refs-and-the-dom.html):** provide only the element type as argument, and use `null` as initial value. In this case, the returned reference will have a read-only `.current` that is managed by React. TypeScript expects you to give this ref to an element's `ref` prop:\n\n```tsx\nfunction Foo() {\n  // - If possible, prefer as specific as possible. For example, HTMLDivElement\n  //   is better than HTMLElement and way better than Element.\n  // - Technical-wise, this returns RefObject<HTMLDivElement>\n  const divRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    // Note that ref.current may be null. This is expected, because you may\n    // conditionally render the ref-ed element, or you may forget to assign it\n    if (!divRef.current) throw Error(\"divRef is not assigned\");\n\n    // Now divRef.current is sure to be HTMLDivElement\n    doSomethingWith(divRef.current);\n  });\n\n  // Give the ref to an element so React can manage it for you\n  return <div ref={divRef}>etc</div>;\n}\n```\n\nIf you are sure that `divRef.current` will never be null, it is also possible to use the non-null assertion operator `!`:\n\n```tsx\nconst divRef = useRef<HTMLDivElement>(null!);\n// Later... No need to check if it is null\ndoSomethingWith(divRef.current);\n```\n\nNote that you are opting out of type safety here - you will have a runtime error if you forget to assign the ref to an element in the render, or if the ref-ed element is conditionally rendered.\n\n<details>\n<summary><b>Tip: Choosing which <code>HTMLElement</code> to use</b></summary>\n  \nRefs demand specificity - it is not enough to just specify any old `HTMLElement`. If you don't know the name of the element type you need, you can check [lib.dom.ts](https://github.com/microsoft/TypeScript/blob/v3.9.5/lib/lib.dom.d.ts#L19224-L19343) or make an intentional type error and let the language service tell you:\n\n![image](https://user-images.githubusercontent.com/6764957/116914284-1c436380-ac7d-11eb-9150-f52c571c5f07.png)\n\n</details>\n\n### Option 2: Mutable value ref\n\n**[To have a mutable value](https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables):** provide the type you want, and make sure the initial value fully belongs to that type:\n\n```tsx\nfunction Foo() {\n  // Technical-wise, this returns MutableRefObject<number | null>\n  const intervalRef = useRef<number | null>(null);\n\n  // You manage the ref yourself (that's why it's called MutableRefObject!)\n  useEffect(() => {\n    intervalRef.current = setInterval(...);\n    return () => clearInterval(intervalRef.current);\n  }, []);\n\n  // The ref is not passed to any element's \"ref\" prop\n  return <button onClick={/* clearInterval the ref */}>Cancel timer</button>;\n}\n```\n\n### See also\n\n- [Related issue by @rajivpunjabi](https://github.com/typescript-cheatsheets/react/issues/388) - [Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwCwAUI7hAHarwCCYYcAvHAAUASn4A+OAG9GjOHAD0CBLLnKGcxHABiwKBzgQwMYGxS4WUACbBWAczgwIcSxFwBXEFlYxkxtgDoVTQBJVmBjZAAbOAA3KLcsOAB3YEjogCNE1jc0-zgAGQBPG3tHOAAVQrAsAGVcKGAjOHTCuDdUErhWNgBabLSUVFQsWBNWA2qoX2hA9VU4AGFKXyx0AFk3H3TIxOwCOAB5dIArLHwgpHcoSm84MGJJmFbgdG74ZcsDVkjC2Y01f7yFQsdjvLAEACM-EwVBg-naWD2AB4ABLlNb5GpgZCsACiO083jEgn6kQAhMJ6HMQfpKJCFpE2IkBNg8HCEci0RisTj8VhCTBiaSKVSVIoAaoLnBQuFgFFYvFEikBpkujkMps4FgAB7VfCdLmY7F4gleOFwAByEHg7U63VYfXVg2Go1MhhG0ygf3mAHVUtF6jgYLtwUdTvguta4Bstjs9mGznCpVcbvB7u7YM90B8vj9vYgLkDqWxaeCAEzQ1n4eHDTnoo2801EknqykyObii5SmpnNifA5GMZmCzWOwOJwudwC3xjKUyiLROKRBLJf3NLJO9KanV64xj0koVifQ08k38s1Sv0DJZBxIx5DbRGhk6J5Nua5mu4PEZPOAvSNgsgnxsHmXZzIgRZyDSYIEAAzJWsI1k+BCovWp58gKcAAD5qmkQqtqKHbyCexoYRecw7IQugcAs76ptCdIQv4KZmoRcjyMRaGkU28A4aSKiUXAwwgpYtEfrcAh0mWzF0ax7bsZx3Lceetx8eqAlYPAMAABa6KJskSXAdKwTJ4kwGxCjyKy-bfK05SrDA8mWVagHAbZeScOY0CjqUE6uOgqDaRAOSfKqOYgb8KiMaZ9GSeCEIMkyMVyUwRHWYc7nSvAgUQEk6AjMQXpReWyWGdFLHeBZHEuTCQEZT8xVwaV8BxZCzUWZQMDvuMghBHASJVnCWhTLYApiH1chIqgxpGeCfCSIxAC+Yj3o+8YvvgSLyNNOLjeBGhTTNdLzVJy3reGMBbTtrB7RoB3XbNBAneCsHLatcbPhdV3GrdB1WYhw3IKNZq-W2DCLYRO7QPAljgsgORcDwVJAA)\n- [Example from Stefan Baumgartner](https://fettblog.eu/typescript-react/hooks/#useref) - [Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wFgAoCzAVwDsNgJa4AVJADxgElaxqYA6sBgALAGIQ01AM4AhfjCYAKAJRwA3hThwA9DrjBaw4CgA2waUjgB3YSLi1qp0wBo4AI35wYSZ6wCeYEgAymhQwGDw1lYoRHCmEBAA1oYA5nCY0HAozAASLACyADI8fDAAoqZIIEi0MFpwaEzS8IZllXAAvIjEMAB0MkjImAA8+cWl-JXVtTAAfEqOzioA3A1NtC1wTPIwirQAwuZoSV1wql1zGg3aenAt4RgOTqaNIkgn0g5ISAAmcDJvBA3h9TsBMAZeFNXjl-lIoEQ6nAOBZ+jddPpPPAmGgrPDEfAUS1pG5hAYvhAITBAlZxiUoRUqjU6m5RIDhOi7iIUF9RFYaqIIP9MlJpABCOCAUHJ0eDzm1oXAAGSKyHtUx9fGzNSacjaPWq6Ea6gI2Z9EUyVRrXV6gC+DRtVu0RBgxuYSnRIzm6O06h0ACpIdlfr9jExSQyOkxTP5GjkPFZBv9bKIDYSmbNpH04ABNFD+CV+nR2636kby+BETCddTlyo27w0zr4HycfC6L0lvUjLH7baHY5Jas7BRMI7AE42uYSUXed6pkY6HtMDulnQruCrCg2oA)\n\n## useImperativeHandle\n\nBased on this [Stackoverflow answer](https://stackoverflow.com/a/69292925/5415299):\n\n```tsx\n// Countdown.tsx\n\n// Define the handle types which will be passed to the forwardRef\nexport type CountdownHandle = {\n  start: () => void;\n};\n\ntype CountdownProps = {};\n\nconst Countdown = forwardRef<CountdownHandle, CountdownProps>((props, ref) => {\n  useImperativeHandle(ref, () => ({\n    // start() has type inference here\n    start() {\n      alert(\"Start\");\n    },\n  }));\n\n  return <div>Countdown</div>;\n});\n```\n\n```tsx\n// The component uses the Countdown component\n\nimport Countdown, { CountdownHandle } from \"./Countdown.tsx\";\n\nfunction App() {\n  const countdownEl = useRef<CountdownHandle>(null);\n\n  useEffect(() => {\n    if (countdownEl.current) {\n      // start() has type inference here as well\n      countdownEl.current.start();\n    }\n  }, []);\n\n  return <Countdown ref={countdownEl} />;\n}\n```\n\n### See also:\n\n- [Using ForwardRefRenderFunction](https://stackoverflow.com/a/62258685/5415299)\n\n## Custom Hooks\n\nIf you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScript will infer a union type (when you actually want different types in each position of the array). Instead, use [TS 3.4 const assertions](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions):\n\n```tsx\nimport { useState } from \"react\";\n\nexport function useLoading() {\n  const [isLoading, setState] = useState(false);\n  const load = (aPromise: Promise<any>) => {\n    setState(true);\n    return aPromise.finally(() => setState(false));\n  };\n  return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?target=5&jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCpAD0ljkwFcA7DYCZuRgZyQBkIKACbBmAcwAUASjgBvCnDhoO3eAG1g3AcNFiANHF4wAyjBQwkAXTgBeRMRgA6HklPmkEzCgA2vKQG4FJRV4b0EhWzgJFAAFHBBNJAAuODjcRIAeFGYATwA+GRs8uSDFIzcLCRgoRiQA0rgiGEYoTlj4xMdMUR9vHIlpW2Lys0qvXzr68kUAX0DpxqRm1rgNLXDdAzDhaxRuYOZVfzgAehO4UUwkKH21ACMICG9UZgMYHLAkCEw4baFrUSqVARb5RB5PF5wAA+cHen1BfykaksFBmQA)\n\nThis way, when you destructure you actually get the right types based on destructure position.\n\n<details>\n<summary><b>Alternative: Asserting a tuple return type</b></summary>\n\nIf you are [having trouble with const assertions](https://github.com/babel/babel/issues/9800), you can also assert or define the function return types:\n\n```tsx\nimport { useState } from \"react\";\n\nexport function useLoading() {\n  const [isLoading, setState] = useState(false);\n  const load = (aPromise: Promise<any>) => {\n    setState(true);\n    return aPromise.finally(() => setState(false));\n  };\n  return [isLoading, load] as [\n    boolean,\n    (aPromise: Promise<any>) => Promise<any>\n  ];\n}\n```\n\nA helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:\n\n```tsx\nfunction tuplify<T extends any[]>(...elements: T) {\n  return elements;\n}\n\nfunction useArray() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() => {}).current;\n  return [numberValue, functionValue]; // type is (number | (() => void))[]\n}\n\nfunction useTuple() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() => {}).current;\n  return tuplify(numberValue, functionValue); // type is [number, () => void]\n}\n```\n\n</details>\n\nNote that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however.\n\n## More Hooks + TypeScript reading:\n\n- https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d\n- https://fettblog.eu/typescript-react/hooks/#useref\n\nIf you are writing a React Hooks library, don't forget that you should also expose your types for users to use.\n\n## Example React Hooks + TypeScript Libraries:\n\n- https://github.com/mweststrate/use-st8\n- https://github.com/palmerhq/the-platform\n- https://github.com/sw-yx/hooks\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n"
  },
  {
    "path": "docs/basic/getting-started/portals.md",
    "content": "---\nid: portals\ntitle: Portals\n---\n\nUsing `ReactDOM.createPortal`:\n\n```tsx\nconst modalRoot = document.getElementById(\"modal-root\") as HTMLElement;\n// assuming in your html file has a div with id 'modal-root';\n\nexport class Modal extends React.Component<{ children?: React.ReactNode }> {\n  el: HTMLElement = document.createElement(\"div\");\n\n  componentDidMount() {\n    modalRoot.appendChild(this.el);\n  }\n\n  componentWillUnmount() {\n    modalRoot.removeChild(this.el);\n  }\n\n  render() {\n    return ReactDOM.createPortal(this.props.children, this.el);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWRYmAEQHkBZObXAo9GAWgBNcZchTQQAdgGd4ICHxQAbBBAjwAvHAFoAriCRiYAOgDmSGAFF5SXfoBCATwCSfABQAiGXPk8cK1wEo4FAk4AAkAFWYAGQsrPRgAbgoAeiTAiQkdYDEjOCy4OwgtKDgACxgQeTZgS1KgwI1gADc4AHdgGBLcvgIPBW9lGHxE4XIkAA9qeDR5IODmWQU4cZg9PmDkbgMAYVxIMTi4AG8KOCX5AC5QiOjLazUNCG07gzQuFZi7tz4m-2GTuFE4HEcXowD48y0+mcAWO5FOp16igGBhQYDAqy2JWqLg6wAkBiQ8j8w1OAF8KP9AXs4gB1aryACqYhkkJg0KO-wRCyRKgMRBkjSQmOxzlx+MJxP+5JGpyIYj4SCg7Nh8LgRBgRTEtG4TGYLzeSAACtAYApRVj8WAcGB8WgsfI+HKADRwMUEokkuDS0lAA)\n\n<details>\n  <summary><b>Using hooks</b></summary>\n\nSame as above but using hooks\n\n```tsx\nimport { useEffect, useRef, ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\nconst modalRoot = document.querySelector(\"#modal-root\") as HTMLElement;\n\ntype ModalProps = {\n  children: ReactNode;\n};\n\nfunction Modal({ children }: ModalProps) {\n  // create div element only once using ref\n  const elRef = useRef<HTMLDivElement | null>(null);\n  if (!elRef.current) elRef.current = document.createElement(\"div\");\n\n  useEffect(() => {\n    const el = elRef.current!; // non-null assertion because it will never be null\n    modalRoot.appendChild(el);\n    return () => {\n      modalRoot.removeChild(el);\n    };\n  }, []);\n\n  return createPortal(children, elRef.current);\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzkgKIBmZSG2RSyZ2y6MAchACZJwC+cZUEEHADkUVBmEBYAFChIsXHDRiUMJAAVoMFABsefAUNHiYAWnaCp0mQHobcFIUL4QwAHYBzOO7gBPCPhQcAAWMCB6ZMA6XMGODnDswABucADuwDDB3uwiIBy6pgIQMMIA3DJoEG6E8HnsuggQxXAAvAkQaC5IbjAAdACO+EhQvgDKSNEY0AAUAEQAxHUFRTCzAJQOhHAAEgAqALIAMiTRIN0w5dbSML5gXPv5OuoCYFttODJwSsFR7GJuAC5ECY2JxLtxLjIyPg3BhgFU4A96jppng0D8dH9ujwgUjdM8IK8Nh9pF87EoVGoEsk4BMkGcenAqjpfEzYVwiO4vGIyJ8lFUarSdPRWgRiPQADx7I4AEWSJ3p5zgAB84G58DodAA+abqzVrS5fYBkODTACEE3ovU6UH+MA2lqQZGtgTtoosnQZfWUqDUCq9c0SSXWkNJYtIFCoMGm0w2LS1uD5X0q1XgE1FjudNrtZtKcHJbiqpj1ekcxFg8LccAARlQULRvPB0pq1UgksMa1wS0m4EthU0+igwHc3OwAMIY9jTCYGntiGCBKux1oJklfde9x6NYq9MR5dsT37TnSzsNfCF87jYADaAF1T3z54uKb6NFpdNN0b9-thMy7becp7cDIIHSOSRAoB4SCgdCsIwJWcAAILDsua78qmcDXoQwQQKkeI6NgxAwKMOF4Y8t6ikwGC9LQozaGo0xkLoxCnl8T5QEuPYSkGWo9mS9j+PgSgoFWzEQHAYD4PAmTAFsPiCUENSqMAaAhGEERRNBZ7rtxNLAOwLSzH2hQDrMWoSjYPF8bg2G4fhcAAGQOaa1lfBK+G8dpG5uUGrneTUvjRC0OBod5YXUoQYA6CgvhArMHhQPpsyYH5YVRegSAAJJqCAhBxWg5zDMlqXecESDAB4oRxQAjAADLVSTBMVXnhV86TsJkQLCHVDXBMIKUta11boAA1glASjnFUAeMN0y1Zg82Lb01VrM1rVhQAXplo5IAAHkCACcB0Det67cMBg3rp5p1fJlwhCCgm7ImaOCzHAswXTdcAStWUkwAiAVBSFw1oGNAgwuwcVgEOvgoKkPxgB9vBVGOOgqSNwXLvGcBESRdmPIxzFIGs3BamgOgQMQFm-TA-1uNd60WVZl0WR51kk9ZP1-QiKNo6DmNxgmuOkfh0wwFAQwk1qtmpIijzU9z9PWeSYiChAJoKQ4w5cZZyQM2sMjcEAA)\n\n</details>\n\nModal Component Usage Example:\n\n```tsx\nimport { useState } from \"react\";\n\nfunction App() {\n  const [showModal, setShowModal] = useState(false);\n\n  return (\n    <div>\n      // you can also put this in your static html file\n      <div id=\"modal-root\"></div>\n      {showModal && (\n        <Modal>\n          <div\n            style={{\n              display: \"grid\",\n              placeItems: \"center\",\n              height: \"100vh\",\n              width: \"100vh\",\n              background: \"rgba(0,0,0,0.1)\",\n              zIndex: 99,\n            }}\n          >\n            I'm a modal!{\" \"}\n            <button\n              style={{ background: \"papyawhip\" }}\n              onClick={() => setShowModal(false)}\n            >\n              close\n            </button>\n          </div>\n        </Modal>\n      )}\n      <button onClick={() => setShowModal(true)}>show Modal</button>\n      // rest of your app\n    </div>\n  );\n}\n```\n\n<details>\n\n<summary><b>Context of Example</b></summary>\n\nThis example is based on the [Event Bubbling Through Portal](https://reactjs.org/docs/portals.html#event-bubbling-through-portals) example of React docs.\n\n</details>\n"
  },
  {
    "path": "docs/basic/linting.md",
    "content": "---\nid: linting\ntitle: Linting\n---\n\n> ⚠️Note that [TSLint is now in maintenance and you should try to use ESLint instead](https://medium.com/palantir/tslint-in-2019-1a144c2317a9). If you are interested in TSLint tips, please check this PR from [@azdanov](https://github.com/typescript-cheatsheets/react/pull/14). The rest of this section just focuses on ESLint. [You can convert TSlint to ESlint with this tool](https://github.com/typescript-eslint/tslint-to-eslint-config).\n\n> ⚠️This is an evolving topic. `typescript-eslint-parser` is no longer maintained and [work has recently begun on `typescript-eslint` in the ESLint community](https://eslint.org/blog/2019/01/future-typescript-eslint) to bring ESLint up to full parity and interop with TSLint.\n\nFollow the TypeScript + ESLint docs at https://github.com/typescript-eslint/typescript-eslint:\n\n```\nyarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint\n```\n\nadd a `lint` script to your `package.json`:\n\n```json\n  \"scripts\": {\n    \"lint\": \"eslint 'src/**/*.ts'\"\n  },\n```\n\nand a suitable `.eslintrc.js` (using `.js` over `.json` here so we can add comments):\n\n```js\nmodule.exports = {\n  env: {\n    es6: true,\n    node: true,\n    jest: true,\n  },\n  extends: \"eslint:recommended\",\n  parser: \"@typescript-eslint/parser\",\n  plugins: [\"@typescript-eslint\"],\n  parserOptions: {\n    ecmaVersion: 2017,\n    sourceType: \"module\",\n  },\n  rules: {\n    indent: [\"error\", 2],\n    \"linebreak-style\": [\"error\", \"unix\"],\n    quotes: [\"error\", \"single\"],\n    \"no-console\": \"warn\",\n    \"no-unused-vars\": \"off\",\n    \"@typescript-eslint/no-unused-vars\": [\n      \"error\",\n      { vars: \"all\", args: \"after-used\", ignoreRestSiblings: false },\n    ],\n    \"@typescript-eslint/explicit-function-return-type\": \"warn\", // Consider using explicit annotations for object literals and function return types even when they can be inferred.\n    \"no-empty\": \"warn\",\n  },\n};\n```\n\nMost of this is taken from [the `tsdx` PR](https://github.com/palmerhq/tsdx/pull/70/files) which is for **libraries**.\n\nMore `.eslintrc.json` options to consider with more options you may want for **apps**:\n\n```json\n{\n  \"extends\": [\n    \"airbnb\",\n    \"prettier\",\n    \"prettier/react\",\n    \"plugin:prettier/recommended\",\n    \"plugin:jest/recommended\",\n    \"plugin:unicorn/recommended\"\n  ],\n  \"plugins\": [\"prettier\", \"jest\", \"unicorn\"],\n  \"parserOptions\": {\n    \"sourceType\": \"module\",\n    \"ecmaFeatures\": {\n      \"jsx\": true\n    }\n  },\n  \"env\": {\n    \"es6\": true,\n    \"browser\": true,\n    \"jest\": true\n  },\n  \"settings\": {\n    \"import/resolver\": {\n      \"node\": {\n        \"extensions\": [\".js\", \".jsx\", \".ts\", \".tsx\"]\n      }\n    }\n  },\n  \"overrides\": [\n    {\n      \"files\": [\"**/*.ts\", \"**/*.tsx\"],\n      \"parser\": \"typescript-eslint-parser\",\n      \"rules\": {\n        \"no-undef\": \"off\"\n      }\n    }\n  ]\n}\n```\n\nAnother great resource is [\"Using ESLint and Prettier in a TypeScript Project\"](https://dev.to/robertcoopercode/using-eslint-and-prettier-in-a-typescript-project-53jb) by @robertcoopercode.\n\nWes Bos is also working on [TypeScript support for his eslint+prettier config.](https://github.com/wesbos/eslint-config-wesbos/issues/68)\n\nIf you're looking for information on Prettier, check out the [Prettier](https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/misc-concerns.md#prettier) guide.\n"
  },
  {
    "path": "docs/basic/recommended/codebases.md",
    "content": "---\nid: codebases\ntitle: Recommended React + TypeScript codebases to learn from\nsidebar_label: Codebases\n---\n\n- Apps\n  - https://github.com/devhubapp/devhub\n  - https://github.com/benawad/codeponder (with [coding livestream!](https://www.youtube.com/watch?v=D8IJOwdNSkc&list=PLN3n1USn4xlnI6kwzI8WrNgSdG4Z6daCq))\n  - https://github.com/cypress-io/cypress-realworld-app\n  - https://github.com/alan2207/bulletproof-react\n- Design Systems/Component Libraries\n  - https://github.com/seek-oss/braid-design-system/ (see [how to use TS to validate props](https://twitter.com/markdalgleish/status/1339863859469955072?s=20))\n  - https://github.com/palantir/blueprint\n  - https://github.com/Shopify/polaris\n  - https://github.com/microsoft/fluentui\n- Libraries\n  - https://github.com/formium/formik/\n  - https://github.com/jaredpalmer/react-fns\n- Misc\n  - https://github.com/NullVoxPopuli/react-vs-ember/tree/master/testing/react\n  - https://github.com/artsy/reaction\n  - https://github.com/artsy/emission (React Native)\n  - [@reach/ui's community typings](https://github.com/reach/reach-ui/pull/105)\n  - https://github.com/pshrmn/curi/tree/master/packages/router\n\nOlder but still worth checking:\n\n- https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/\n- https://github.com/contiamo/operational-ui\n\nReact Boilerplates:\n\n- https://github.com/rwieruch/nextjs-firebase-authentication: Next.js + Firebase Starter: styled, tested, typed, and authenticated\n- [@jpavon/react-scripts-ts](https://github.com/jpavon/react-scripts-ts) alternative react-scripts with all TypeScript features using [ts-loader](https://github.com/TypeStrong/ts-loader)\n- [webpack config tool](https://webpack.jakoblind.no/) is a visual tool for creating webpack projects with React and TypeScript\n- <https://github.com/innFactory/create-react-app-material-typescript-redux> ready to go template with [Material-UI](https://material-ui.com/), routing and Redux\n\nReact Native Boilerplates: _contributed by [@spoeck](https://github.com/typescript-cheatsheets/react/pull/20)_\n\n- https://github.com/GeekyAnts/react-native-seed\n- https://github.com/lopezjurip/ReactNativeTS\n- https://github.com/emin93/react-native-template-typescript\n- <https://github.com/Microsoft/TypeScript-React-Native-Starter>\n\nTS Library Codebases to study\n\n- https://github.com/Azure/azure-sdk-for-js\n- https://github.com/sindresorhus/is\n- https://github.com/probot/probot\n- https://github.com/intuit/auto\n- https://github.com/polymer/tools\n- https://github.com/nteract/nteract\n- https://github.com/pgilad/leasot\n- https://github.com/JasonEtco/actions-toolkit\n- https://github.com/ferdaber/typescript-bootstrap/\n- https://github.com/contiamo/operational-scripts\n- https://github.com/nobrainr/morphism\n- https://github.com/slackapi/node-slack-sdk\n"
  },
  {
    "path": "docs/basic/recommended/resources.md",
    "content": "---\nid: resources\ntitle: Other React + TypeScript resources\nsidebar_label: Other resources\n---\n\n- me! <https://twitter.com/swyx>\n- https://www.freecodecamp.org/news/how-to-build-a-todo-app-with-react-typescript-nodejs-and-mongodb/\n- <https://github.com/piotrwitek/react-redux-typescript-guide> - **HIGHLY HIGHLY RECOMMENDED**, i wrote this repo before knowing about this one, this has a lot of stuff I don't cover, including **REDUX** and **JEST**.\n- [10 Bad TypeScript Habits](https://startup-cto.net/10-bad-typescript-habits-to-break-this-year/):\n  1. not using `\"strict\": true`\n  2. using `||` for default values when we have `??`\n  3. Using `any` instead of `unknown` for API responses\n  4. using `as` assertion instead of Type Guards (`function isFoo(obj: unknown): obj is Foo {}`)\n  5. `as any` in tests\n  6. Marking optional properties instead of modeling which combinations exist by extending interfaces\n  7. One letter generics\n  8. Non-boolean `if (nonboolean)` checks\n  9. bangbang checks `if (!!nonboolean)`\n  10. `!= null` to check for `null` and `undefined`\n- [Ultimate React Component Patterns with TypeScript 2.8](https://levelup.gitconnected.com/ultimate-react-component-patterns-with-typescript-2-8-82990c516935)\n- [Basarat's TypeScript gitbook has a React section](https://basarat.gitbook.io/typescript/tsx/react) with an [Egghead.io course](https://egghead.io/courses/use-typescript-to-develop-react-applications) as well.\n- [Palmer Group's TypeScript + React Guidelines](https://github.com/palmerhq/typescript) as well as Jared's other work like [disco.chat](https://github.com/jaredpalmer/disco.chat)\n- [Sindre Sorhus' TypeScript Style Guide](https://github.com/sindresorhus/typescript-definition-style-guide)\n- [TypeScript React Starter Template by Microsoft](https://github.com/Microsoft/TypeScript-React-Starter) A starter template for TypeScript and React with a detailed README describing how to use the two together. Note: this doesn't seem to be frequently updated anymore.\n- [Steve Kinney's React and TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/react-typescript/)\n- [Brian Holt's Intermediate React course on Frontend Masters (paid)](https://frontendmasters.com/courses/intermediate-react/converting-the-app-to-typescript/) - Converting App To TypeScript Section\n- [Mike North's Production TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/production-typescript/)\n- [TSX Guide](https://jenil.github.io/chota/) by [gojutin](https://github.com/gojutin/www.tsx.guide)\n- TypeScript conversion:\n  - [Lyft's React-To-TypeScript conversion CLI](https://github.com/lyft/react-javascript-to-typescript-transform)\n  - [Gustav Wengel's blogpost - converting a React codebase to TypeScript](http://www.gustavwengel.dk/converting-typescript-to-javascript-part-1)\n  - [Microsoft React TypeScript conversion guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide)\n- [Matt Pocock's Beginner's Typescript Tutorial](https://github.com/total-typescript/beginners-typescript-tutorial)\n- [Matt Pocock's React with TypeScript Tutorial](https://www.totaltypescript.com/tutorials/react-with-typescript)\n- [You?](https://github.com/typescript-cheatsheets/react/issues/new).\n"
  },
  {
    "path": "docs/basic/recommended/talks.md",
    "content": "---\nid: talks\ntitle: Recommended React + TypeScript talks\nsidebar_label: Talks\n---\n\n- [Ultimate React Component Patterns with TypeScript](https://www.youtube.com/watch?v=_PBQ3if6Fmg), by Martin Hochel, GeeCon Prague 2018\n- [How to Build React Apps with TypeScript](https://youtu.be/LJzGGmu5APA?si=YNzy7T_8yj7TuXxS), by ClearEdge Tech Talk 2022\n- [Create a More Readable React Codebase Using TypeScript](https://youtu.be/nkJbGgieALI?si=IFZZIMEiXz7AsiBv), by Emma Brillhart 2019\n- [Advanced TypeScript with React](https://youtu.be/zQfD4ZxxyKA?si=FmrgOq667svX6C9O), by Nikhil Verma 2019\n- [Senior Typescript Features You don't Know About - clean-code](https://www.youtube.com/watch?v=Y4u97vJqmhM), by CoderOne 2023\n- [React & TypeScript - Course for Beginners](https://www.youtube.com/watch?v=FJDVKeh7RJI), by FreeCodeCamp 2022\n- [TypeScript + React](https://www.youtube.com/watch?v=1ZnrX3wiNTU), by Chris Toomey 2019\n- [Mastering React Hooks](https://www.youtube.com/watch?v=zM_ZiSl2n2E), by Jack Herrington 2021\n- [Using Hooks and codegen](https://www.youtube.com/watch?v=cdsnzfJUqm0) by Tejas Kumar 2019\n\n- Please help contribute to this new section!\n"
  },
  {
    "path": "docs/basic/setup.md",
    "content": "---\nid: setup\ntitle: Setup\n---\n\n## Prerequisites\n\nYou can use this cheatsheet for reference at any skill level, but basic understanding of React and TypeScript is assumed. Here is a list of prerequisites:\n\n- Basic understanding of [React](https://react.dev/).\n- Familiarity with [TypeScript Basics](https://www.typescriptlang.org/docs/handbook/2/basic-types.html) and [Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html).\n\nIn the cheatsheet we assume you are using the latest versions of React and TypeScript.\n\n## React and TypeScript starter kits\n\nReact has documentation for [how to start a new React project](https://react.dev/learn/start-a-new-react-project) with some of the most popular frameworks. Here's how to start them with TypeScript:\n\n- [Next.js](https://nextjs.org/docs/basic-features/typescript): `npx create-next-app@latest --ts`\n- [Remix](https://remix.run/docs/tutorials/blog): `npx create-remix@latest`\n- [Gatsby](https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/): `npm init gatsby --ts`\n- [Expo](https://docs.expo.dev/guides/typescript/): `npx create-expo-app -t with-typescript`\n\n## Try React and TypeScript online\n\nThere are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.\n\n- [TypeScript playground](https://www.typescriptlang.org/play?target=8&jsx=4#code/JYWwDg9gTgLgBAbzgVwM4FMDKMCGN0A0KGAogGZnoDG8AvnGVBCHAORTo42sDcAsAChB6AB6RYcKhAB2qeAGEIyafihwAvHAAUASg0A+RILiSZcuAG0pymEQwxFNgLobiWXPi0AGHfyECTNHRyShotXQMjAJM4ABMIKmQQdBUAOhhgGAAbdFcAAwBNJUks4CoAa3RYuAASBGsVegzk1Dy-E1pfQWM4DhhkKGltHpMAHn0RmNGwfSLkErLK6vqlRrhm9FRRgHoZybGAI2QYGBk4GXlSivUECPVDe0cVLQb4AGo4AEYdWgnomJil0WcGS+zgOyOJxkfwBOxhcC6AlogiAA)\n- [StackBlitz](https://stackblitz.com/fork/react-ts)\n- [CodeSandbox](https://ts.react.new/)\n"
  },
  {
    "path": "docs/basic/troubleshooting/learn-ts.md",
    "content": "---\nid: learn_ts\ntitle: \"Time to Really Learn TypeScript\"\nsidebar_label: Time to Really Learn TypeScript\n---\n\nBelieve it or not, we have only barely introduced TypeScript here in this cheatsheet. If you are still facing TypeScript troubleshooting issues, it is likely that your understanding of TS is still too superficial.\n\nThere is a whole world of generic type logic that you will eventually get into, however it becomes far less dealing with React than just getting good at TypeScript so it is out of scope here. But at least you can get productive in React now :)\n\nIt is worth mentioning some resources to help you get started:\n\n- Step through the 40+ examples under [the playground's](http://www.typescriptlang.org/play/index.html) Examples section, written by @Orta\n- Anders Hejlsberg's overview of TS: https://www.youtube.com/watch?v=ET4kT88JRXs\n- Marius Schultz: https://blog.mariusschulz.com/series/typescript-evolution with an [Egghead.io course](https://egghead.io/courses/advanced-static-types-in-typescript)\n- Basarat's Deep Dive: https://basarat.gitbook.io/typescript/\n- Axel Rauschmeyer's [Tackling TypeScript](https://exploringjs.com/tackling-ts/)\n- Rares Matei: [Egghead.io course](https://egghead.io/courses/practical-advanced-typescript)'s advanced TypeScript course on Egghead.io is great for newer typescript features and practical type logic applications (e.g. recursively making all properties of a type `readonly`)\n- Learn about [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ&feature=youtu.be)\n- Shu Uesugi: [TypeScript for Beginner Programmers](https://ts.chibicode.com/)\n- Here is another [TypeScript Error Guide](https://github.com/threehams/typescript-error-guide/) that you can check for your errors.\n"
  },
  {
    "path": "docs/basic/troubleshooting/non-ts-files.md",
    "content": "---\nid: non_ts_files\ntitle: \"Troubleshooting Handbook: Globals, Images and other non-TS files\"\nsidebar_label: Globals, Images and other non-TS files\n---\n\nUse [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).\n\nIf, say, you are using a third party JS script that attaches on to the `window` global, you can extend `Window`:\n\n```ts\ndeclare global {\n  interface Window {\n    MyVendorThing: MyVendorType;\n  }\n}\n```\n\nLikewise if you wish to \"import\" an image or other non TS/TSX file:\n\n```ts\n// declaration.d.ts\n// anywhere in your project, NOT the same name as any of your .ts/tsx files\ndeclare module \"*.png\";\n\n// importing in a tsx file\nimport * as logo from \"./logo.png\";\n```\n\nNote that `tsc` cannot bundle these files for you, you will have to use Webpack or Parcel.\n\nRelated issue: https://github.com/Microsoft/TypeScript-React-Starter/issues/12 and [StackOverflow](https://stackoverflow.com/a/49715468/4216035)\n"
  },
  {
    "path": "docs/basic/troubleshooting/official-typings-bugs.md",
    "content": "---\nid: official_typings_bugs\ntitle: Fixing bugs in official typings\nsidebar_label: Fixing bugs in official typings\n---\n\nIf you run into bugs with your library's official typings, you can copy them locally and tell TypeScript to use your local version using the \"paths\" field. In your `tsconfig.json`:\n\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"mobx-react\": [\"../typings/modules/mobx-react\"]\n    }\n  }\n}\n```\n\n[Thanks to @adamrackis for the tip.](https://twitter.com/AdamRackis/status/1024827730452520963)\n\nIf you just need to add an interface, or add missing members to an existing interface, you don't need to copy the whole typing package. Instead, you can use [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html):\n\n```tsx\n// my-typings.ts\ndeclare module \"plotly.js\" {\n  interface PlotlyHTMLElement {\n    removeAllListeners(): void;\n  }\n}\n\n// MyComponent.tsx\nimport { PlotlyHTMLElement } from \"plotly.js\";\n\nconst f = (e: PlotlyHTMLElement) => {\n  e.removeAllListeners();\n};\n```\n\nYou don't always have to implement the module, you can simply import the module as `any` for a quick start:\n\n```tsx\n// my-typings.ts\ndeclare module \"plotly.js\"; // each of its imports are `any`\n```\n\nBecause you don't have to explicitly import this, this is known as an [ambient module declaration](https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html#pitfalls-of-namespaces-and-modules). You can do AMD's in a script-mode `.ts` file (no imports or exports), or a `.d.ts` file anywhere in your project.\n\nYou can also do ambient variable and ambient type declarations:\n\n```ts\n// ambient utility type\ntype ToArray<T> = T extends unknown[] ? T : T[];\n// ambient variable\ndeclare let process: {\n  env: {\n    NODE_ENV: \"development\" | \"production\";\n  };\n};\nprocess = {\n  env: {\n    NODE_ENV: \"production\",\n  },\n};\n```\n\nYou can see examples of these included in the built in type declarations in the `lib` field of `tsconfig.json`\n"
  },
  {
    "path": "docs/basic/troubleshooting/operators.md",
    "content": "---\nid: operators\ntitle: \"Troubleshooting Handbook: Operators\"\nsidebar_label: Operators\n---\n\n- `typeof` and `instanceof`: type query used for refinement\n- `keyof`: get keys of an object. `keyof T` is an operator to tell you what values of `k` can be used for `obj[k]`.\n  - [Some misconceptions here](https://twitter.com/SeaRyanC/status/1418678670739218438?s=20).\n- `O[K]`: property lookup\n- `[K in O]`: mapped types\n- `+` or `-` or `readonly` or `?`: addition and subtraction and readonly and optional modifiers\n- `x ? Y : Z`: Conditional types for generic types, type aliases, function parameter types\n- `!`: Nonnull assertion for nullable types\n- `=`: Generic type parameter default for generic types\n- `as`: type assertion\n- `is`: type guard for function return types\n\nConditional Types are a difficult topic to get around so here are some extra resources:\n\n- fully walked through explanation https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/\n- Bailing out and other advanced topics https://github.com/sw-yx/ts-spec/blob/master/conditional-types.md\n- Basarat's video https://www.youtube.com/watch?v=SbVgPQDealg&list=PLYvdvJlnTOjF6aJsWWAt7kZRJvzw-en8B&index=2&t=0s\n- [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ&feature=youtu.be)\n"
  },
  {
    "path": "docs/basic/troubleshooting/ts-config.md",
    "content": "---\nid: tsconfig\ntitle: \"Troubleshooting Handbook: tsconfig.json\"\nsidebar_label: tsconfig.json\n---\n\nYou can find [all the Compiler options in the TypeScript docs](https://www.typescriptlang.org/docs/handbook/compiler-options.html). [The new TS docs also has per-flag annotations of what each does](https://www.typescriptlang.org/tsconfig#allowSyntheticDefaultImports). This is the setup I roll with for APPS (not libraries - for libraries you may wish to see the settings we use in `tsdx`):\n\n```json\n{\n  \"compilerOptions\": {\n    \"incremental\": true,\n    \"outDir\": \"build/lib\",\n    \"target\": \"es5\",\n    \"module\": \"esnext\",\n    \"lib\": [\"DOM\", \"ESNext\"],\n    \"sourceMap\": true,\n    \"importHelpers\": true,\n    \"declaration\": true,\n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noImplicitReturns\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"allowJs\": false,\n    \"jsx\": \"react\",\n    \"moduleResolution\": \"node\",\n    \"baseUrl\": \"src\",\n    \"forceConsistentCasingInFileNames\": true,\n    \"esModuleInterop\": true,\n    \"suppressImplicitAnyIndexErrors\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"experimentalDecorators\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"build\", \"scripts\"]\n}\n```\n\nYou can find more [recommended TS config here](https://github.com/tsconfig/bases).\n\nPlease open an issue and discuss if there are better recommended choices for React.\n\nSelected flags and why we like them:\n\n- `esModuleInterop`: disables namespace imports (`import * as foo from \"foo\"`) and enables CJS/AMD/UMD style imports (`import fs from \"fs\"`)\n- `strict`: `strictPropertyInitialization` forces you to initialize class properties or explicitly declare that they can be undefined. You can opt out of this with a definite assignment assertion.\n- `\"typeRoots\": [\"./typings\", \"./node_modules/@types\"]`: By default, TypeScript looks in `node_modules/@types` and parent folders for third party type declarations. You may wish to override this default resolution so you can put all your global type declarations in a special `typings` folder.\n\nCompilation time grows linearly with size of codebase. For large projects, you will want to use [Project References](https://www.typescriptlang.org/docs/handbook/project-references.html). See our [ADVANCED](https://react-typescript-cheatsheet.netlify.app/docs/advanced) cheatsheet for commentary.\n"
  },
  {
    "path": "docs/basic/troubleshooting/types.md",
    "content": "---\nid: types\ntitle: \"Troubleshooting Handbook: Types\"\nsidebar_label: Types\n---\n\n> ⚠️ Have you read [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ?) Your answer might be there!\n\nFacing weird type errors? You aren't alone. This is the hardest part of using TypeScript with React. Be patient - you are learning a new language after all. However, the more you get good at this, the less time you'll be working _against_ the compiler and the more the compiler will be working _for_ you!\n\nTry to avoid typing with `any` as much as possible to experience the full benefits of TypeScript. Instead, let's try to be familiar with some of the common strategies to solve these issues.\n\n## Union Types and Type Guarding\n\nUnion types are handy for solving some of these typing problems:\n\n```tsx\nclass App extends React.Component<\n  {},\n  {\n    count: number | null; // like this\n  }\n> {\n  state = {\n    count: null,\n  };\n  render() {\n    return <div onClick={() => this.increment(1)}>{this.state.count}</div>;\n  }\n  increment = (amt: number) => {\n    this.setState((state) => ({\n      count: (state.count || 0) + amt,\n    }));\n  };\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2K0EAK48YALjg89IAEZIocAD6m91agG44AejdxqwANZI4MAAWwHSaKhQAfFrkinQwKNxwALzRijr6hiZmTmHOmkT81gAUAJSpaUQwelA8cLJ8wABucBA8Yt5oPklKpclRQSEiwDxoRCAyRQCMJSoRSgN0InEJSCK6BjAqsm4NjRF5MXDhh8OjSOOGyXBFKCDGDpbWZUlRStoBwYt0SDAAyvHcIrLRIva5vQ5pODrTLXYGraHwWz2AAMZQA1HBbjB3ioSiUDooVAcVEA)\n\n**Type Guarding**: Sometimes Union Types solve a problem in one area but create another downstream. If `A` and `B` are both object types, `A | B` means \"either A or B\" (not both at once - that would be an intersection type `A & B`). TypeScript will only let you access properties that exist on both types unless you use type guards to narrow the type. Learn how to write checks, guards, and assertions (also see the Conditional Rendering section below). For example:\n\n```ts\ninterface Admin {\n  role: string;\n}\ninterface User {\n  email: string;\n}\n\n// Method 1: use `in` keyword\nfunction redirect(user: Admin | User) {\n  if (\"role\" in user) {\n    // use the `in` operator for typeguards since TS 2.7+\n    routeToAdminPage(user.role);\n  } else {\n    routeToHomePage(user.email);\n  }\n}\n\n// Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enough\nfunction isAdmin(user: Admin | User): user is Admin {\n  return (user as any).role !== undefined;\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoC4AOxiSk3STgEEATEGuAbwrjhwAbJAC44AZxhQaAcwDcFAL5Va9RmmYBVcfR584SECmCCxk6dXlKKFTAFdqGYBGoCIdugBUI7TtQAKKDJIABTiwDLUwJjA9ACUeuT80XBhEVExugC8OQR2OlAIEML4CbxJ-AJIMHZQrvi+NGQVinDWlOT2jjDOrjgeSN4AErhIgcFpkdGxUGX6KZMZM3A5WQSGxoKliZVVNXUEIyBIYEFIzfzK5FcUAPS3cACy1QAWEGxwAIxi+cwABjQ-nAANZIACeAHdoGxbA4nC4qmxgEQMCFflAxI1XAAfODaeI7ODREIAIiESBJRNc6LKcHucF+cBgL3+gLgEDA9BQMGgcEwvJgYM5MjsKCgbHEEhoGjgngAynAAEwAOgA7ABqfT8fpeHwcGjjULo5XkuIKFoGQQ6Qna9y6o5jM5ogrKjYmM36K43cj057M95KsRofI8vCCzlwEVitgAGjgbAgSElzOY4hQxyZL1kVPZgjYunlcAAbvRwi5JbyISyiHAAdQgcBxLQDNR3DIXrDur0ieIsc76Jj9Ti8QU4j8Cj3WEPCUR9q5+1A4ChJShqGC4ibiswAIS5Bz5mLUJAw65AA)\n\nMethod 2 is also known as [User-Defined Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) and can be really handy for readable code. This is how TS itself refines types with `typeof` and `instanceof`.\n\nIf you need `if...else` chains or the `switch` statement instead, it should \"just work\", but look up [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions) if you need help. (See also: [Basarat's writeup](https://basarat.gitbook.io/typescript/type-system/discriminated-unions)). This is handy in typing reducers for `useReducer` or Redux.\n\n## Optional Types\n\nIf a component has an optional prop, add a question mark and assign during destructure (or use defaultProps).\n\n```tsx\nclass MyComponent extends React.Component<{\n  message?: string; // like this\n}> {\n  render() {\n    const { message = \"default\" } = this.props;\n    return <div>{message}</div>;\n  }\n}\n```\n\nYou can also use a `!` character to assert that something is not undefined, but this is not encouraged.\n\n_Something to add? [File an issue](https://github.com/typescript-cheatsheets/react/issues/new) with your suggestions!_\n\n## Enum Types\n\n**We recommend avoiding using enums as far as possible**.\n\nEnums have a few [documented issues](https://fettblog.eu/tidy-typescript-avoid-enums/) (the TS team [agrees](https://twitter.com/orta/status/1348966323271987201?s=20)). A simpler alternative to enums is just declaring a union type of string literals:\n\n```tsx\nexport declare type Position = \"left\" | \"right\" | \"top\" | \"bottom\";\n```\n\nIf you must use enums, remember that enums in TypeScript default to numbers. You will usually want to use them as strings instead:\n\n```tsx\nexport enum ButtonSizes {\n  default = \"default\",\n  small = \"small\",\n  large = \"large\",\n}\n\n// usage\nexport const PrimaryButton = (\n  props: Props & React.HTMLProps<HTMLButtonElement>\n) => <Button size={ButtonSizes.default} {...props} />;\n```\n\n## Type Assertion\n\nSometimes you know better than TypeScript that the type you're using is narrower than it thinks, or union types need to be asserted to a more specific type to work with other APIs, so assert with the `as` keyword. This tells the compiler you know better than it does.\n\n```tsx\nclass MyComponent extends React.Component<{\n  message: string;\n}> {\n  render() {\n    const { message } = this.props;\n    return (\n      <Component2 message={message as SpecialMessageType}>{message}</Component2>\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgGU61gUAbAWSQGduUBzJABVa9ALwFuMKMAB2-fAG4KFOTCRRM6egAUcYbnADeFOHBA8+ggFxwpM+XAA+cAK6yAJkkxykH5eQAvirkaBCyUnAAwriQskiyMABMtsjoMAB0AGJRADx6EAYAfHASABRG5pYCSIEAlKUlZaZwuR7AAG5FLWa5ABYAjEVGFrw1gbkA9IPd5L2T7V0UdSFobCi8cBzUMeDhCfBIAB7qnoZpGBm7cQe5JnNVYzZ20nL8AYEl92ZEnhplDW+ZjgYQi8Eqoys9ECpTgMD6wG4GTA+m4AWBcCIMFcUFkcGaDwxuWu+0SSUeULEI2qgjgG0YzFYnBpwlEn2pT1qUxJ8TJswxdXRcGCQSAA)\n\nNote that you cannot assert your way to anything - basically it is only for refining types. Therefore it is not the same as \"casting\" a type.\n\nYou can also assert a property is non-null, when accessing it:\n\n```ts\nelement.parentNode!.removeChild(element); // ! before the period\nmyFunction(document.getElementById(dialog.id!)!); // ! after the property accessing\nlet userID!: string; // definite assignment assertion... be careful!\n```\n\nOf course, try to actually handle the null case instead of asserting :)\n\n## Simulating Nominal Types\n\nTS' structural typing is handy, until it is inconvenient. However you can simulate nominal typing with [`type branding`](https://basarat.gitbook.io/typescript/main-1/nominaltyping):\n\n```ts\ntype OrderID = string & { readonly brand: unique symbol };\ntype UserID = string & { readonly brand: unique symbol };\ntype ID = OrderID | UserID;\n```\n\nWe can create these values with the Companion Object Pattern:\n\n```ts\nfunction OrderID(id: string) {\n  return id as OrderID;\n}\nfunction UserID(id: string) {\n  return id as UserID;\n}\n```\n\nNow TypeScript will disallow you from using the wrong ID in the wrong place:\n\n```ts\nfunction queryForUser(id: UserID) {\n  // ...\n}\nqueryForUser(OrderID(\"foobar\")); // Error, Argument of type 'OrderID' is not assignable to parameter of type 'UserID'\n```\n\nIn future you can use the `unique` keyword to brand. [See this PR](https://github.com/microsoft/TypeScript/pull/33038).\n\n## Intersection Types\n\nAdding two types together can be handy, for example when your component is supposed to mirror the props of a native component like a `button`:\n\n```tsx\nexport interface PrimaryButtonProps {\n  label: string;\n}\nexport const PrimaryButton = (\n  props: PrimaryButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>\n) => {\n  // do custom buttony stuff\n  return <button {...props}> {props.label} </button>;\n};\n```\n\n_Playground [here](https://www.typescriptlang.org/play?ssl=4&ssc=1&pln=12&pc=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCipAD0ljmADsYkpN0k4AFKUFKAE8AQgFcYMCE14QwAZzgBvCnDgAbFACMkagFxw5MPkwDmAbgoBfanWjw0Uwzz4gBI8ZKZwAvHAAUKnBgOPL6vPxCYhJSMvJwAGSIxDAAdFGeABIAKgCyADIAghJ8muJIcgA82fnpUgCiakggSCwAfBQAlD6tSoEA9H1wACYQcGiihrhwpdFMggYwopiYgUSLUF4VM55KKXvBsnKWPYoH8ika2mqWcBV921KtFuSWQA)_\n\nYou can also use Intersection Types to make reusable subsets of props for similar components:\n\n```tsx\ntype BaseProps = {\n   className?: string,\n   style?: React.CSSProperties\n   name: string // used in both\n}\ntype DogProps = {\n  tailsCount: number\n}\ntype HumanProps = {\n  handsCount: number\n}\nexport const Human = (props: BaseProps & HumanProps) => // ...\nexport const Dog = (props: BaseProps & DogProps) => // ...\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgCEUBnJABRzGbgF44BvCnGFoANi2YA5FCCQB+AFxxmMKMAB2AcwA0Q4Suqj5S5OhgA6AMIBlaxwh1YwJMz1x1MpEpVqtcAPT+cACurAAmcBpwAEYQMAAWFAC+VLT0ACIQmvZcvAJ6MCjAosyWEMHqMErqwSDRSFDJqXRwABK1KOo53HyC5MLxnWGl5ZXVtfWN5CnkSAAekLBwaBDqKm0d6ibEFgBilgA8TKzdcABkGyCd3QB8eQAUAJS8d-d6B2HAAG4BNxSPFAo80W8BWa3gmU02zM5n2RxY7E43AukNuD2ePFe70+P38f3IjyAA)\n\nMake sure not to confuse Intersection Types (which are **and** operations) with Union Types (which are **or** operations).\n\n## Union Types\n\nThis section is yet to be written (please contribute!). Meanwhile, see our [commentary on Union Types usecases](https://github.com/typescript-cheatsheets/react/blob/main/README.md#union-types-and-type-guarding).\n\nThe ADVANCED cheatsheet also has information on Discriminated Union Types, which are helpful when TypeScript doesn't seem to be narrowing your union type as you expect.\n\n## Overloading Function Types\n\nSpecifically when it comes to functions, you may need to overload instead of union type. The most common way function types are written uses the shorthand:\n\n```ts\ntype FunctionType1 = (x: string, y: number) => number;\n```\n\nBut this doesn't let you do any overloading. If you have the implementation, you can put them after each other with the function keyword:\n\n```ts\nfunction pickCard(x: { suit: string; card: number }[]): number;\nfunction pickCard(x: number): { suit: string; card: number };\nfunction pickCard(x): any {\n  // implementation with combined signature\n  // ...\n}\n```\n\nHowever, if you don't have an implementation and are just writing a `.d.ts` definition file, this won't help you either. In this case you can forego any shorthand and write them the old-school way. The key thing to remember here is as far as TypeScript is concerned, `functions are just callable objects with no key`:\n\n```ts\ntype pickCard = {\n  (x: { suit: string; card: number }[]): number;\n  (x: number): { suit: string; card: number };\n  // no need for combined signature in this form\n  // you can also type static properties of functions here eg `pickCard.wasCalled`\n};\n```\n\nNote that when you implement the actual overloaded function, the implementation will need to declare the combined call signature that you'll be handling, it won't be inferred for you. You can readily see examples of overloads in DOM APIs, e.g. `createElement`.\n\n[Read more about Overloading in the Handbook.](https://www.typescriptlang.org/docs/handbook/functions.html#overloads)\n\n## Using Inferred Types\n\nLeaning on TypeScript's Type Inference is great... until you realize you need a type that was inferred, and have to go back and explicitly declare types/interfaces so you can export them for reuse.\n\nFortunately, with `typeof`, you won't have to do that. Just use it on any value:\n\n```tsx\nconst [state, setState] = useState({\n  foo: 1,\n  bar: 2,\n}); // state's type inferred to be {foo: number, bar: number}\n\nconst someMethod = (obj: typeof state) => {\n  // grabbing the type of state even though it was inferred\n  // some code using obj\n  setState(obj); // this works\n};\n```\n\n## Using Partial Types\n\nWorking with slicing state and props is common in React. Again, you don't really have to go and explicitly redefine your types if you use the `Partial` generic type:\n\n```tsx\nconst [state, setState] = useState({\n  foo: 1,\n  bar: 2,\n}); // state's type inferred to be {foo: number, bar: number}\n\n// NOTE: stale state merging is not actually encouraged in useState\n// we are just demonstrating how to use Partial here\nconst partialStateUpdate = (obj: Partial<typeof state>) =>\n  setState({ ...state, ...obj });\n\n// later on...\npartialStateUpdate({ foo: 2 }); // this works\n```\n\n<details>\n<summary><b>Minor caveats on using <code>Partial</code></b></summary>\n\nNote that there are some TS users who don't agree with using `Partial` as it behaves today. See [subtle pitfalls of the above example here](https://twitter.com/ferdaber/status/1084798596027957248), and check out this long discussion on [why @types/react uses Pick instead of Partial](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365).\n\n</details>\n\n## The Types I need weren't exported!\n\nThis can be annoying but here are ways to grab the types!\n\n- Grabbing the Prop types of a component: Use `React.ComponentProps` and `typeof`, and optionally `Omit` any overlapping types\n\n```tsx\nimport { Button } from \"library\"; // but doesn't export ButtonProps! oh no!\ntype ButtonProps = React.ComponentProps<typeof Button>; // no problem! grab your own!\ntype AlertButtonProps = Omit<ButtonProps, \"onClick\">; // modify\nconst AlertButton = (props: AlertButtonProps) => (\n  <Button onClick={() => alert(\"hello\")} {...props} />\n);\n```\n\nYou may also use [`ComponentPropsWithoutRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L774) (instead of ComponentProps) and [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770) (if your component specifically forwards refs)\n\n- Grabbing the return type of a function: use `ReturnType`:\n\n```tsx\n// inside some library - return type { baz: number } is inferred but not exported\nfunction foo(bar: string) {\n  return { baz: 1 };\n}\n\n//  inside your app, if you need { baz: number }\ntype FooReturn = ReturnType<typeof foo>; // { baz: number }\n```\n\nIn fact you can grab virtually anything public: [see this blogpost from Ivan Koshelev](http://ikoshelev.azurewebsites.net/search/id/11/Pragmatic-uses-of-TypeScript-type-system-My-type-of-type)\n\n```ts\nfunction foo() {\n  return {\n    a: 1,\n    b: 2,\n    subInstArr: [\n      {\n        c: 3,\n        d: 4,\n      },\n    ],\n  };\n}\n\ntype InstType = ReturnType<typeof foo>;\ntype SubInstArr = InstType[\"subInstArr\"];\ntype SubInstType = SubInstArr[0];\n\nlet baz: SubInstType = {\n  c: 5,\n  d: 6, // type checks ok!\n};\n\n//You could just write a one-liner,\n//But please make sure it is forward-readable\n//(you can understand it from reading once left-to-right with no jumps)\ntype SubInstType2 = ReturnType<typeof foo>[\"subInstArr\"][0];\nlet baz2: SubInstType2 = {\n  c: 5,\n  d: 6, // type checks ok!\n};\n```\n\n- TS also ships with a `Parameters` utility type for extracting the parameters of a function\n- for anything more \"custom\", the `infer` keyword is the basic building block for this, but takes a bit of getting used to. Look at the source code for the above utility types, and [this example](https://twitter.com/mgechev/status/1211030455224422401?s=20) to get the idea. Basarat [also has a good video on `infer`](https://www.youtube.com/watch?v=ijK-1R-LFII&list=PLYvdvJlnTOjF6aJsWWAt7kZRJvzw-en8B&index=3&t=0s).\n\n## The Types I need don't exist!\n\nWhat's more annoying than modules with unexported types? Modules that are **untyped**!\n\n> Before you proceed - make sure you have checked that types don't exist in [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) or [TypeSearch](https://microsoft.github.io/TypeSearch/)\n\nFret not! There are more than a couple of ways in which you can solve this problem.\n\n### Slapping `any` on everything\n\nA **lazier** way would be to create a new type declaration file, say `typedec.d.ts`– if you don't already have one. Ensure that the path to file is resolvable by TypeScript by checking the `include` array in the `tsconfig.json` file at the root of your directory.\n\n```json\n// inside tsconfig.json\n{\n  // ...\n  \"include\": [\n    \"src\" // automatically resolves if the path to declaration is src/typedec.d.ts\n  ]\n  // ...\n}\n```\n\nWithin this file, add the `declare` syntax for your desired module, say `my-untyped-module`– to the declaration file:\n\n```ts\n// inside typedec.d.ts\ndeclare module \"my-untyped-module\";\n```\n\nThis one-liner alone is enough if you just need it to work without errors. A even hackier, write-once-and-forget way would be to use `\"*\"` instead which would then apply the `Any` type for all existing and future untyped modules.\n\nThis solution works well as a workaround if you have less than a couple untyped modules. Anything more, you now have a ticking type-bomb in your hands. The only way of circumventing this problem would be to define the missing types for those untyped modules as explained in the following sections.\n\n### Autogenerate types\n\nYou can use TypeScript with `--allowJs` and `--declaration` to see TypeScript's \"best guess\" at the types of the library.\n\nIf this doesn't work well enough, use [`dts-gen`](https://github.com/Microsoft/dts-gen) to use the runtime shape of the object to accurately enumerate all available properties. This tends to be very accurate, BUT the tool does not yet support scraping JSDoc comments to populate additional types.\n\n```bash\nnpm install -g dts-gen\ndts-gen -m <your-module>\n```\n\nThere are other automated JS to TS conversion tools and migration strategies - see [our MIGRATION cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/migration/from_js).\n\n### Typing Exported Hooks\n\nTyping Hooks is just like typing pure functions.\n\nThe following steps work under two assumptions:\n\n- You have already created a type declaration file as stated earlier in the section.\n- You have access to the source code - specifically the code that directly exports the functions you will be using. In most cases, it would be housed in an `index.js` file.\n  Typically you need a minimum of **two** type declarations (one for **Input Prop** and the other for **Return Prop**) to define a hook completely. Suppose the hook you wish to type follows the following structure,\n\n```js\n// ...\nconst useUntypedHook = (prop) => {\n  // some processing happens here\n  return {\n    /* ReturnProps */\n  };\n};\nexport default useUntypedHook;\n```\n\nthen, your type declaration should most likely follow the following syntax.\n\n```ts\ndeclare module 'use-untyped-hook' {\n  export interface InputProps { ... }   // type declaration for prop\n  export interface ReturnProps { ... } // type declaration for return props\n  export default function useUntypedHook(\n    prop: InputProps\n    // ...\n  ): ReturnProps;\n}\n```\n\n<details>\n<summary><b>For instance, the <a href=\"https://github.com/donavon/use-dark-mode\">useDarkMode hook</a> exports the functions that follows a similar structure.</b></summary>\n\n```js\n// inside src/index.js\nconst useDarkMode = (\n  initialValue = false, // -> input props / config props to be exported\n  {\n    // -> input props / config props to be exported\n    element,\n    classNameDark,\n    classNameLight,\n    onChange,\n    storageKey = \"darkMode\",\n    storageProvider,\n    global,\n  } = {}\n) => {\n  // ...\n  return {\n    // -> return props to be exported\n    value: state,\n    enable: useCallback(() => setState(true), [setState]),\n    disable: useCallback(() => setState(false), [setState]),\n    toggle: useCallback(() => setState((current) => !current), [setState]),\n  };\n};\nexport default useDarkMode;\n```\n\nAs the comments suggest, exporting these config props and return props following the aforementioned structure will result in the following type export.\n\n```ts\ndeclare module \"use-dark-mode\" {\n  /**\n   * A config object allowing you to specify certain aspects of `useDarkMode`\n   */\n  export interface DarkModeConfig {\n    classNameDark?: string; // A className to set \"dark mode\". Default = \"dark-mode\".\n    classNameLight?: string; // A className to set \"light mode\". Default = \"light-mode\".\n    element?: HTMLElement; // The element to apply the className. Default = `document.body`\n    onChange?: (val?: boolean) => void; // Override the default className handler with a custom callback.\n    storageKey?: string; // Specify the `localStorage` key. Default = \"darkMode\". Set to `null` to disable persistent storage.\n    storageProvider?: WindowLocalStorage; // A storage provider. Default = `localStorage`.\n    global?: Window; // The global object. Default = `window`.\n  }\n  /**\n   * An object returned from a call to `useDarkMode`.\n   */\n  export interface DarkMode {\n    readonly value: boolean;\n    enable: () => void;\n    disable: () => void;\n    toggle: () => void;\n  }\n  /**\n   * A custom React Hook to help you implement a \"dark mode\" component for your application.\n   */\n  export default function useDarkMode(\n    initialState?: boolean,\n    config?: DarkModeConfig\n  ): DarkMode;\n}\n```\n\n</details>\n\n### Typing Exported Components\n\nIn case of typing untyped class components, there's almost no difference in approach except for the fact that after declaring the types, you export the extend the type using `class UntypedClassComponent extends React.Component<UntypedClassComponentProps, any> {}` where `UntypedClassComponentProps` holds the type declaration.\n\nFor instance, [sw-yx's Gist on React Router 6 types](https://gist.github.com/sw-yx/37a6a3d248c2d4031801f0d568904df8) implemented a similar method for typing the then untyped RR6.\n\n```ts\ndeclare module \"react-router-dom\" {\n  import * as React from 'react';\n  // ...\n  type NavigateProps<T> = {\n    to: string | number,\n    replace?: boolean,\n    state?: T\n  }\n  //...\n  export class Navigate<T = any> extends React.Component<NavigateProps<T>>{}\n  // ...\n```\n\nFor more information on creating type definitions for class components, you can refer to this [post](https://templecoding.com/blog/2016/03/31/creating-typescript-typings-for-existing-react-components) for reference.\n\n## Frequent Known Problems with TypeScript\n\nJust a list of stuff that React developers frequently run into, that TS has no solution for. Not necessarily TSX only.\n\n### TypeScript doesn't narrow after an object element null check\n\n[![https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg&name=medium](https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg&name=medium)](https://mobile.twitter.com/tannerlinsley/status/1390409931627499523)\n\nRef: https://mobile.twitter.com/tannerlinsley/status/1390409931627499523. see also https://github.com/microsoft/TypeScript/issues/9998\n\n### TypeScript doesn't let you restrict the type of children\n\nGuaranteeing typesafety for this kind of API isn't possible:\n\n```tsx\n<Menu>\n  <MenuItem/> {/* ok */}\n  <MenuLink/> {/* ok */}\n  <div> {/* error */}\n</Menu>\n```\n\nSource: https://twitter.com/ryanflorence/status/1085745787982700544?s=20\n"
  },
  {
    "path": "docs/basic/troubleshooting/utilities.md",
    "content": "---\nid: utilities\ntitle: \"Troubleshooting Handbook: Utilities\"\nsidebar_label: Utilities\n---\n\nThese are all built in, [see source in es5.d.ts](https://github.com/microsoft/TypeScript/blob/33a34e5b96bfe086266f4765ab9789a2a02507f9/src/lib/es5.d.ts#L1523-L1637):\n\n- `Awaited`: emulate the behavior of `await`\n- `Capitalize`: convert first character of string literal type to uppercase\n- `ConstructorParameters`: a tuple of class constructor's parameter types\n- `Exclude`: exclude a type from another type\n- `Extract`: select a subtype that is assignable to another type\n- `InstanceType`: the instance type you get from a `new`ing a class constructor\n- `Lowercase`: convert string literal type to lowercase\n- `NonNullable`: exclude `null` and `undefined` from a type\n- `Omit`: construct a type with the properties of another type.\n- `OmitThisParameter`: remove the 'this' parameter from a function type.\n- `Parameters`: a tuple of a function's parameter types\n- `Partial`: Make all properties in an object optional\n- `Readonly`: Make all properties in an object readonly\n- `ReadonlyArray`: Make an immutable array of the given type\n- `Pick`: A subtype of an object type with a subset of its keys\n- `Record`: A map from a key type to a value type\n- `Required`: Make all properties in an object required\n- `ReturnType`: A function's return type\n- `ThisParameterType`: extract the type of the 'this' parameter of a function type\n- `ThisType`: marker for contextual 'this' type\n- `Uncapitalize`: convert first character of string literal type to lowercase\n- `Uppercase`: convert string literal type to uppercase\n"
  },
  {
    "path": "docs/hoc/excluding-props.md",
    "content": "---\nid: excluding_props\nsidebar_label: Excluding Props\ntitle: \"Section 2: Excluding Props\"\n---\n\nThis is covered in passing in Section 1 but we focus on it here as it is such a common issue. HOCs often inject props to premade components. The problem we want to solve is having the HOC-wrapped-component exposing a type that reflects the reduced surface area of props - without manually retyping the HOC every time. This involves some generics, fortunately with some helper utilities.\n\nSay we have a component:\n\n```tsx\ntype DogProps {\n  name: string\n  owner: string\n}\nfunction Dog({name, owner}: DogProps) {\n  return <div> Woof: {name}, Owner: {owner}</div>\n}\n```\n\nAnd we have a `withOwner` HOC that injects the `owner`:\n\n```tsx\nconst OwnedDog = withOwner(\"swyx\")(Dog);\n```\n\nWe want to type `withOwner` such that it will pass through the types of any component like `Dog`, into the type of `OwnedDog`, minus the `owner` property it injects:\n\n```tsx\ntypeof OwnedDog; // we want this to be equal to { name: string }\n\n<Dog name=\"fido\" owner=\"swyx\" />; // this should be fine\n<OwnedDog name=\"fido\" owner=\"swyx\" />; // this should have a typeError\n<OwnedDog name=\"fido\" />; // this should be fine\n\n// and the HOC should be reusable for completely different prop types!\n\ntype CatProps = {\n  lives: number;\n  owner: string;\n};\nfunction Cat({ lives, owner }: CatProps) {\n  return (\n    <div>\n      {\" \"}\n      Meow: {lives}, Owner: {owner}\n    </div>\n  );\n}\n\nconst OwnedCat = withOwner(\"swyx\")(Cat);\n\n<Cat lives={9} owner=\"swyx\" />; // this should be fine\n<OwnedCat lives={9} owner=\"swyx\" />; // this should have a typeError\n<OwnedCat lives={9} />; // this should be fine\n```\n\nSo how do we type `withOwner`?\n\n1. We get the types of the component: `keyof T`\n2. We `Exclude` the property we want to mask: `Exclude<keyof T, 'owner'>`, this leaves you with a list of names of properties you want on the wrapped component e.g. `name`\n3. (optional) Use intersection types if you have more to exclude: `Exclude<keyof T, 'owner' | 'otherprop' | 'moreprop'>`\n4. Names of properties aren't quite the same as properties themselves, which also have an associated type. So we use this generated list of names to `Pick` from the original props: `Pick<keyof T, Exclude<keyof T, 'owner'>>`, this leaves you with the new, filtered props, e.g. `{ name: string }`\n5. (optional) Instead of writing this manually each time, we could use this utility: `type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>`\n6. Now we write the HOC as a generic function:\n\n```tsx\nfunction withOwner(owner: string) {\n  return function <T extends { owner: string }>(\n    Component: React.ComponentType<T>\n  ) {\n    return function (props: Omit<T, \"owner\">): React.JSX.Element {\n      const newProps = { ...props, owner } as T;\n      return <Component {...newProps} />;\n    };\n  };\n}\n```\n\n(_[Link to TS Playground](https://www.typescriptlang.org/play/?strictFunctionTypes=false&jsx=1&ssl=1&ssc=1&pln=47&pc=49#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wG4AoczAVwDsNgJa4B3YGACwHkXakoAFBF78AXHADOMKMFoBzAJRwA3uThwiMalGY16MRswA8AFThIAHjCS0AJhJVxhfKOKkz5cAL4A+AWvU4AGFcSD5aGHFkdBgAOhDwJhsYEwBPMCRTHwClVUCNJC0dOD0GJjgBMBwwCXEuEHZTABoCZ358HyVxACkAZQANWIBRABskEGSVAPyAehmAQTgYdKQ4NAh+NEM4YAc+NDQkCQkUKFS4ACMkNBRqCVW0jN60GTB4Ww2JWgByeABrWjCJYcFDwTireqNEwtfBtKAdOAAahUcPEsXRXjgAF44CZpoF1rQpHA+CwAArVBw45RwdGxKoQGotOHeOAoBwmCj5dSabTGBJhSbKOmkimMiSYmY+LmBLwyuXkLyUZYZYKgsU1bFTdQjYAANyO4lo1BAVygMtRkmksjkFAVpQM5SCoIENN1BokzJEUG84mdMA1ElyAV5xX8+SMtn12W5KnwBCVsYAskhhOJlO6jl4WjwXOm4YnAkYZlG9TG4Ao7ZRCcTc0hbP6tWxOHXBPgJCxUhZ8AoBP7K5QjI3MxIscoAJyYuFY9ud7twKWkBczYG7SQcCDUEa2S6rTCyJDkIx1huguAjseTpzemcdrvxxfL1cOCQbrc7kEGtlLFZDKA4KAjxPYd9SOS9JWlJ9ODXV9N23XcSgPShyBVVYABEIDkQNtRJFAJjca15ACS13BtRUqDoMpmAwuRXVoPCkC9FwvHEGjA2DHlCj5OBI2jOAAHUIAgTB03oiZszgVt829Lxi1LbIlRreATxopt2G4b0BFne9exogdB1UsSkBnfcPnjadtPnR85mfdc4J3K5EL4ICRFsQyGJM4AzOvFxbznB9IJs6CXzfeDP1WFAfwyP8AJcvg3Mw3CJk87zrJXYK7PfBD9z4IA)_)\n\nNote that we need to do a type coercion here.\n\nThis is because TypeScript does not know that merging `Omit<T, \"owner\">` and `{owner: \"whatever\"}` is the same as `T`.\n\n[See this GitHub issue for more.](https://github.com/microsoft/TypeScript/issues/35858)\n\n## Generic solution\n\nThe above snippet can be modified to create a generic solution to inject any arbitrary props;\n\n```typescript\nfunction withInjectedProps<U extends Record<string, unknown>>(\n  injectedProps: U\n) {\n  return function <T extends U>(Component: React.ComponentType<T>) {\n    return function (props: Omit<T, keyof U>): React.JSX.Element {\n      //A type coercion is necessary because TypeScript doesn't know that the Omit<T, keyof U> + {...injectedProps} = T\n      const newProps = { ...props, ...injectedProps } as T;\n      return <Component {...newProps} />;\n    };\n  };\n}\n```\n\n(_[Link to TS Playground](https://www.typescriptlang.org/play?strictFunctionTypes=false&jsx=1#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wG4AoczAVwDsNgJa4B3YGACwElaArJDEgAmABRxgAzgB4AqnCQAPGElpCJiAdCFSJMKMFoBzADRw6Aa1oQWtAHy24ACgP9Bo8RIBccGQEo4AN7kcHBEMNRQzDT0MIzMUgAq8koqaj62jsEhcADCuJC0KjDeyOgwAHR54ExFCQCeYEiJtln+QdmhSOGRcNEMTE5gHt4A8iDsiabmSHUQmOn+3gBSAMoAGuUAogA2SCBFgVkdAPTHAIJwMA1IcGgQSFBocXDA6oVoaEgSEihQdXAAIwEKGoEhu9UaKzQ+jA8CE9wktAA5PBLNZLhwUPBODcxhMEqZ8NZClB8A4ANSBYkPbzlOkAXzgAF44Akjtk7rRdHBCiwxBBJMzAnA6eUhgKJKZRS4BMp3BK4IyUOoEhQOiEwhF4lUCgcAqLefzJIzjrY1dl6ebLeR6ZQro1clijeoWe04NtgAA3L7eWjUEBAqDm6lQby6fRGCjWvqxAY5LGOALur1fUwhxXeeMwZ1tLKanqZDpSIRelrqwL4Ai28sAWSQ1m8AQ93ok9NMIxsNKpnag1eyUmOJc9ZbgvijduucBE2xQhWzHiFbtoKH2Yb0BkMpDgNsoMee09nXUTy-2jO8B7nOcOGq6Wqc7OLpbgjSgEiYbxXN1egRPSHpA6HEcx23W1yE5bkO0KIQsyFNhOB4Vw5WdRMQ28fAAQgAF8HpXxHCzYDKCkGDmy+JkAgATkZEMmXwCQWDqBRK1NLdTgxb8JA4CBqG2IRARuTADCQcgpEg4RiJTCQyMouBqNo+jGLgZjFOONj1A4rieLgTFvTgFBLmuTYoBwKBhNE6CsWTFspJNM1lNUuB1O43igV6QTKHA+AzIvLpYPYbg+FlYRkICVCCAwrCcMcbyYGA1jNgURo3HkIzoDgABaXTtk4LjDA4Ux2CRN4IHgMBfliNBuN+bZ-iIFAhBQAFdnKbcgA)_)\n\n## Without coercion\n\n```typescript\nfunction withOwner(owner: string) {\n  return function <T extends { owner: string }>(\n    Component: React.ComponentType<T>\n  ): React.ComponentType<Omit<T, \"owner\"> & { owner?: never }> {\n    return function (props) {\n      const newProps = { ...props, owner };\n      return <Component {...newProps} />;\n    };\n  };\n}\n```\n\n(_[Link to TS Playground](https://www.typescriptlang.org/play?strictFunctionTypes=false&jsx=1#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wG4AoczAVwDsNgJa4B3YGACwHkXakoAFBF78AXHADOMKMFoBzAJRwA3uThwiMalGY16MRswA8AFThIAHjCS0AJhJVxhfKOKkz5cAL4A+AWvU4AGFcSD5aGHFkdBgAOhDwJhsYEwBPMCRTHwCFKOI4hLDktIyjLhB2UwAaAmd+fB84ADIVOqgAfnE+ADd+XxUA9U1tXToGJjgBMBwwCSVVQMC0Jik4PhYABRmHAF5HWIPpiFmatu8KRaGkLR04I0KkiJUD2PWt44kvOAB6HwvArz-QHkLyUGDpJDBFAwd6zOB7BZwAA2wF6Ei61BAACN+P82m5pLI5BRgXpxswgtCBMpkaikBJTiIoN5xJSYdt5gFhrd-IsjLZUdlLip8ARQcKALJIYTiZQotFeGo8FyytriwJGb4C7pCuAKEmUZa0VbKpC2Nnw1jsbhMgT4CQsVIWfAKARs-WUe7Q2lonbKACcXzaO3tjudPz+P2+cE4wAcEg4EGoSNscBxcEwsiQ5DKInN3vl9L9gacTJDDqdot+pCjMY4cckieTqY4KF6cBQMYhAFEoDgoDnTfn4IWJMWvtXa7H402U2nIZm+JRyOCMnAACIQOSwhyI2goEBIAkeOQBfGSQnyEFUMYGCabuTU-eHxkuLziB87zlXG7GbWNAB1CAIEwWVnyQRU4FNVxWiZLxNX-a8jRNPMH0tNhOGgu0K2dV0Hw9T00PAkNM1sCBRWDUNKwjGtvmjadGyTOd00XbNcz4WwiIPJASOAMiKLLKjw0nOi6wbBMmJbNtIU7VckF7ftB1Qrc1m43j+Joqd6xnST5wzLMgA)_)\n\n## Learn More\n\nWe will need to extract lessons from here in future but here they are:\n\n- https://medium.com/@xfor/typescript-react-hocs-context-api-cb46da611f12\n- https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb\n- https://www.matthewgerstman.com/tech/ts-tricks-higher-order-components/\n"
  },
  {
    "path": "docs/hoc/full-example.md",
    "content": "---\nid: full_example\nsidebar_label: Full HOC Example\ntitle: \"Full HOC Example\"\n---\n\n> This is an HOC example for you to copy and paste. If certain pieces don't make sense for you, head to [the React HOC Docs intro](https://react-typescript-cheatsheet.netlify.app/docs/hoc/react_hoc_docs/) to get a detailed walkthrough via a complete translation of the React docs in TypeScript.\n\nSometimes you want a simple way to inject props from somewhere else (either a global store or a provider) and don't want to continually pass down the props for it. Context is great for it, but then the values from the context can only be used in your `render` function. A HoC will provide these values as props.\n\n**The injected props**\n\n```ts\ninterface WithThemeProps {\n  primaryColor: string;\n}\n```\n\n**Usage in the component**\n\nThe goal is to have the props available on the interface for the component, but subtracted out for the consumers of the component when wrapped in the HoC.\n\n```ts\ninterface Props extends WithThemeProps {\n  children?: React.ReactNode;\n}\n\nclass MyButton extends React.Component<Props> {\n  public render() {\n    // Render an the element using the theme and other props.\n  }\n\n  private someInternalMethod() {\n    // The theme values are also available as props here.\n  }\n}\n\nexport default withTheme(MyButton);\n```\n\n**Consuming the Component**\n\nNow when consuming the component you can omit the `primaryColor` prop or override the one provided through context.\n\n```tsx\n<MyButton>Hello button</MyButton> // Valid\n<MyButton primaryColor=\"#333\">Hello Button</MyButton> // Also valid\n```\n\n**Declaring the HoC**\n\nThe actual HoC.\n\n```tsx\nexport function withTheme<T extends WithThemeProps = WithThemeProps>(\n  WrappedComponent: React.ComponentType<T>\n) {\n  // Try to create a nice displayName for React Dev Tools.\n  const displayName =\n    WrappedComponent.displayName || WrappedComponent.name || \"Component\";\n\n  // Creating the inner component. The calculated Props type here is the where the magic happens.\n  const ComponentWithTheme = (props: Omit<T, keyof WithThemeProps>) => {\n    // Fetch the props you want to inject. This could be done with context instead.\n    const themeProps = useTheme();\n\n    // props comes afterwards so the can override the default ones.\n    return <WrappedComponent {...themeProps} {...(props as T)} />;\n  };\n\n  ComponentWithTheme.displayName = `withTheme(${displayName})`;\n\n  return ComponentWithTheme;\n}\n```\n\nNote that the `{...(props as T)}` assertion is needed because of a current bug in TS 3.2 https://github.com/Microsoft/TypeScript/issues/28938#issuecomment-450636046\n\nHere is a more advanced example of a dynamic higher order component that bases some of its parameters on the props of the component being passed in:\n\n```tsx\n// inject static values to a component so that they're always provided\nexport function inject<TProps, TInjectedKeys extends keyof TProps>(\n  Component: React.JSXElementConstructor<TProps>,\n  injector: Pick<TProps, TInjectedKeys>\n) {\n  return function Injected(props: Omit<TProps, TInjectedKeys>) {\n    return <Component {...(props as TProps)} {...injector} />;\n  };\n}\n```\n\n### Using `forwardRef`\n\nFor \"true\" reusability you should also consider exposing a ref for your HOC. You can use `React.forwardRef<Ref, Props>` as documented in [the basic cheatsheet](https://github.com/typescript-cheatsheets/react/blob/main/README.md#forwardrefcreateref), but we are interested in more real world examples. [Here is a nice example in practice](https://gist.github.com/OliverJAsh/d2f462b03b3e6c24f5588ca7915d010e) from @OliverJAsh (note - it still has some rough edges, we need help to test this out/document this).\n\n### Supporting `defaultProps` of Wrapped Component\n\nIf this is something you need, please see [the stale discussion we had](https://github.com/typescript-cheatsheets/react/issues/86) and comment with your requirements. We will pick this up again if needed.\n"
  },
  {
    "path": "docs/hoc/index.md",
    "content": "---\nid: intro\nsidebar_label: Intro\ntitle: HOC Cheatsheet\n---\n\n**This HOC Cheatsheet** compiles all available knowledge for writing Higher Order Components with React and TypeScript.\n\n- We will map closely to [the official docs on HOCs](https://reactjs.org/docs/higher-order-components.html) initially\n- While hooks exist, many libraries and codebases still have a need to type HOCs.\n- Render props may be considered in the future\n- The goal is to write HOCs that offer type safety while not getting in the way.\n\nThere are a lot of use cases where an HOC is used. For example:\n\n- HOCs can wrap components to check if a user is authenticated before rendering, or to restrict access based on user roles.\n- An HOC can conditionally render components based on feature flags or A/B testing.\n- An HOC can provide translation functionality to components.\n- An HOC can add logging or analytics tracking to components without modifying their core logic.\n\nHere is a base HOC example you can copy right away:\n\n```jsx\n\ntype PropsAreEqual<P> = (\n  prevProps: Readonly<P>,\n  nextProps: Readonly<P>\n) => boolean;\n\nconst withSampleHoC = <P extends {}>(\n  component: {\n    (props: P): Exclude<React.ReactNode, undefined>;\n    displayName?: string;\n  },\n  propsAreEqual?: PropsAreEqual<P> | false,\n\n  componentName = component.displayName ?? component.name\n): {\n  (props: P): React.JSX.Element;\n  displayName: string;\n} => {\n\n  function WithSampleHoc(props: P) {\n    //Do something special to justify the HoC.\n    return component(props) as React.JSX.Element;\n  }\n\n  WithSampleHoc.displayName = `withSampleHoC(${componentName})`;\n\n  let wrappedComponent = propsAreEqual === false ? WithSampleHoc : React.memo(WithSampleHoc, propsAreEqual);\n\n  //copyStaticProperties(component, wrappedComponent);\n\n  return wrappedComponent as typeof WithSampleHoc\n};\n```\n\nThis code meets these criteria:\n\n1. Allows a component to return valid elements (`strings | array | boolean | null | number`) and not just `React.JSX.Element | null`.\n2. Wraps it in a memo unless you opt out.\n3. Removes the nested component, so React Dev tools will just show one component.\n4. Indicates with `displayName` in React Dev Tool with an annotation that this is a component wrapped in two HoCs\n5. Optional: Copies over static properties that might have been defined on the original component.\n"
  },
  {
    "path": "docs/hoc/react-hoc-docs.md",
    "content": "---\nid: react_hoc_docs\nsidebar_label: React HOC docs in TypeScript\ntitle: \"Section 1: React HOC docs in TypeScript\"\n---\n\nIn this first section we refer closely to [the React docs on HOCs](https://reactjs.org/docs/higher-order-components.html) and offer direct TypeScript parallels.\n\n## Docs Example: [Use HOCs For Cross-Cutting Concerns](https://reactjs.org/docs/higher-order-components.html#use-hocs-for-cross-cutting-concerns)\n\n<details>\n\n<summary>\n<b>Misc variables referenced in the example below</b>\n</summary>\n\n```tsx\n/** dummy child components that take anything */\nconst Comment = (_: any) => null;\nconst TextBlock = Comment;\n\n/** dummy Data */\ntype CommentType = { text: string; id: number };\nconst comments: CommentType[] = [\n  {\n    text: \"comment1\",\n    id: 1,\n  },\n  {\n    text: \"comment2\",\n    id: 2,\n  },\n];\nconst blog = \"blogpost\";\n\n/** mock data source */\nconst DataSource = {\n  addChangeListener(e: Function) {\n    // do something\n  },\n  removeChangeListener(e: Function) {\n    // do something\n  },\n  getComments() {\n    return comments;\n  },\n  getBlogPost(id: number) {\n    return blog;\n  },\n};\n/** type aliases just to deduplicate */\ntype DataType = typeof DataSource;\n// type TODO_ANY = any;\n\n/** utility types we use */\ntype Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;\n// type Optionalize<T extends K, K> = Omit<T, keyof K>;\n\n/** Rewritten Components from the React docs that just uses injected data prop */\nfunction CommentList({ data }: WithDataProps<typeof comments>) {\n  return (\n    <div>\n      {data.map((comment: CommentType) => (\n        <Comment comment={comment} key={comment.id} />\n      ))}\n    </div>\n  );\n}\ninterface BlogPostProps extends WithDataProps<string> {\n  id: number;\n}\nfunction BlogPost({ data, id }: BlogPostProps) {\n  return (\n    <div key={id}>\n      <TextBlock text={data} />;\n    </div>\n  );\n}\n```\n\n[View in TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCgeirhgAskBnJOFIuxuMHMJuiHABGrYADsAVkgxIAJsICenVgAkA8gGEK4mEiiZ0rAOrAGAERQwUABV5MAPABUAfHADeFOHFmWUALjhHAG44Gm9fOGB+AHMkMT1gNAoAX2paR0j+BlYYBTBWCExwqzS4a0zlbjs4QsqAdygUMHz5NFxIeLF4BksK8Uw9IllSjQrstgwAVxQAG0iuvQM0AqLxhqaWuDbwCE74AApJlnkYQWjGoW8kA0mZmFsIPjhsXEiYAEoKJAAPSFhnyZiDDAXZwOqmegAZUmQiYaCgwDAMBBYicABoynAfroxLJ+CZzL4HnwnM4MRpnPtPKFaAwonQ8qxZjMIHV+EcBPMBlAyhihJN4OcUJdxrl8jUikZGs05Bp2rs4vAWGB2JYkDMlOCGBABW95rp9AkxNEwRDKv09HFlhKytSpRtZfK9gFkOgYAA6ABSkIAGgBRGZIECKuViJgwKCTDDQezWVwAMjgGjR1LCLEDGAsVgqKABQNOPMw0ECqdoPEe-Hprtkuw1wmkKCOohg+H4RBQNbEdfETGAshWlTQMxQTCY1PT0hgWf8cCp5C8Xh8VkhOqgywCYqQtWnK8ma6QKfnC-LfBdqE7Gvs3p97oAMsAhI0oAoALIoMQoWKyACCMAjD4FZh7GTOA1BAUxYwxAAiJcUCg5wEOpd44AAXlcRwKGQjwjzCcYQE-RIKkYIgAmvO8HyfV930-ORf3-fldH4cEZjmKwAGsci4TcbXtFo5R2PY2FxOAiCYCAZgAN2bfh+xuO4qgrUs2GiFAe26LgT34WoCXoacMTqehEnoCoJCOdSCgRaJxFmTFuK1Yz8Fg-ARKDCApPkF48FMNskAAR0mYAiGDLoxyPbjiX4FC4DI+9H3YKiPy-OiEQYoCQLAiDrGg2D4OcIJqW4yErF0VD3GpRdfACYJqWSfKjyIGA9zELZh1HOAdOnLFvhxPFEGID1+I6RVYzsDEirVVxsIXLZdnDSNoygfZNICCKsPKhcmEmfJFs0946umrw6SYd16HfWRAw0U7jVYKKjpOs6Lqu2J3SEcRZH2I69vWw7DOO8M1VKqaDoqqwAgnTNfH2HdV2WDFdu+uBavW1JKCPLxtiGrozD7F8dS6Ur9mQtC4GhvdlndDtZEu99YnvcM4j0D7fvu3FHpppAvtR6aMYVLoTBYgBVMQQDx+AosJ1DnAR0n93dIK3KQanrrpnFGbuq7zsVp6Obq9aNbZ66CaJqW0YXO6WBgcbdH2IHgdgsH1Unacod8Xd9wxO74dNrxkk59aiFxRm1u9mlKjFcQTSLHkmB4c8I84KJ3U0zJ3VTuApOfGbwEDb53XrcMwRQJRLPoeAxFZMZBFMgvuNMNh+HfBQEbCWDTRYuBw2AduRAZfI0EYNAOOGEOGqa2cEa8exeL4p1FWKFAULcc3iqQd1YOSdxU-dJnE+TkchIUd4N6oE3gc56aUZ9-bQ9HqBmo63w6pR6gACoX7gdRRiOGjTQYJNZ5CnAF+VAvi-GgPANoYZ4D8WCjAFWOloSwnhIiZEoIor2UQXCBESIURzi8DAxUKtDxeBdsuGGSAAjTkcIyY2JNXbkPdLEGABCQqE0wrrcgPw-gQNmvAAAQiyaI1gIDhgQTCLBKCUSlQweI5BODdh4LgAIiAQiREwGIbOGW646FWGofkOGdgAgZRgPYZRqjwwRWyr4eCxt1paNXkwsxwjwxLTsO6PsnxyB7SAA)\n\n</details>\n\nExample HOC from React Docs translated to TypeScript\n\n```tsx\n// these are the props to be injected by the HOC\ninterface WithDataProps<T> {\n  data: T; // data is generic\n}\n// T is the type of data\n// P is the props of the wrapped component that is inferred\n// C is the actual interface of the wrapped component (used to grab defaultProps from it)\nexport function withSubscription<T, P extends WithDataProps<T>, C>(\n  // this type allows us to infer P, but grab the type of WrappedComponent separately without it interfering with the inference of P\n  WrappedComponent: React.JSXElementConstructor<P> & C,\n  // selectData is a functor for T\n  // props is Readonly because it's readonly inside of the class\n  selectData: (\n    dataSource: typeof DataSource,\n    props: Readonly<React.JSX.LibraryManagedAttributes<C, Omit<P, \"data\">>>\n  ) => T\n) {\n  // the magic is here: React.JSX.LibraryManagedAttributes will take the type of WrapedComponent and resolve its default props\n  // against the props of WithData, which is just the original P type with 'data' removed from its requirements\n  type Props = React.JSX.LibraryManagedAttributes<C, Omit<P, \"data\">>;\n  type State = {\n    data: T;\n  };\n  return class WithData extends React.Component<Props, State> {\n    constructor(props: Props) {\n      super(props);\n      this.handleChange = this.handleChange.bind(this);\n      this.state = {\n        data: selectData(DataSource, props),\n      };\n    }\n\n    componentDidMount = () => DataSource.addChangeListener(this.handleChange);\n\n    componentWillUnmount = () =>\n      DataSource.removeChangeListener(this.handleChange);\n\n    handleChange = () =>\n      this.setState({\n        data: selectData(DataSource, this.props),\n      });\n\n    render() {\n      // the typing for spreading this.props is... very complex. best way right now is to just type it as any\n      // data will still be typechecked\n      return (\n        <WrappedComponent data={this.state.data} {...(this.props as any)} />\n      );\n    }\n  };\n  // return WithData;\n}\n\n/** HOC usage with Components */\nexport const CommentListWithSubscription = withSubscription(\n  CommentList,\n  (DataSource: DataType) => DataSource.getComments()\n);\n\nexport const BlogPostWithSubscription = withSubscription(\n  BlogPost,\n  (DataSource: DataType, props: Omit<BlogPostProps, \"data\">) =>\n    DataSource.getBlogPost(props.id)\n);\n```\n\n## Docs Example: [Don’t Mutate the Original Component. Use Composition.](https://reactjs.org/docs/higher-order-components.html#dont-mutate-the-original-component-use-composition)\n\nThis is pretty straightforward - make sure to assert the passed props as `T` [due to the TS 3.2 bug](https://github.com/Microsoft/TypeScript/issues/28938#issuecomment-450636046).\n\n```tsx\nfunction logProps<T>(WrappedComponent: React.ComponentType<T>) {\n  return class extends React.Component {\n    componentWillReceiveProps(\n      nextProps: React.ComponentProps<typeof WrappedComponent>\n    ) {\n      console.log(\"Current props: \", this.props);\n      console.log(\"Next props: \", nextProps);\n    }\n    render() {\n      // Wraps the input component in a container, without mutating it. Good!\n      return <WrappedComponent {...(this.props as T)} />;\n    }\n  };\n}\n```\n\n## Docs Example: [Pass Unrelated Props Through to the Wrapped Component](https://reactjs.org/docs/higher-order-components.html#convention-pass-unrelated-props-through-to-the-wrapped-component)\n\nNo TypeScript specific advice needed here.\n\n## Docs Example: [Maximizing Composability](https://reactjs.org/docs/higher-order-components.html#convention-maximizing-composability)\n\nHOCs can take the form of Functions that return Higher Order Components that return Components.\n\n`connect` from `react-redux` has a number of overloads you can take inspiration [from in the source](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/bc0c933415466b34d2de5790f7cd6418f676801e/types/react-redux/v5/index.d.ts#L77).\n\nHere we build our own mini `connect` to understand HOCs:\n\n<details>\n\n<summary>\n<b>Misc variables referenced in the example below</b>\n</summary>\n\n```tsx\n/** utility types we use */\ntype Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;\n\n/** dummy Data */\ntype CommentType = { text: string; id: number };\nconst comments: CommentType[] = [\n  {\n    text: \"comment1\",\n    id: 1,\n  },\n  {\n    text: \"comment2\",\n    id: 2,\n  },\n];\n/** dummy child components that take anything */\nconst Comment = (_: any) => null;\n/** Rewritten Components from the React docs that just uses injected data prop */\nfunction CommentList({ data }: WithSubscriptionProps<typeof comments>) {\n  return (\n    <div>\n      {data.map((comment: CommentType) => (\n        <Comment comment={comment} key={comment.id} />\n      ))}\n    </div>\n  );\n}\n```\n\n</details>\n\n```tsx\nconst commentSelector = (_: any, ownProps: any) => ({\n  id: ownProps.id,\n});\nconst commentActions = () => ({\n  addComment: (str: string) =>\n    comments.push({ text: str, id: comments.length }),\n});\n\nconst ConnectedComment = connect(commentSelector, commentActions)(CommentList);\n\n// these are the props to be injected by the HOC\ninterface WithSubscriptionProps<T> {\n  data: T;\n}\nfunction connect(mapStateToProps: Function, mapDispatchToProps: Function) {\n  return function <T, P extends WithSubscriptionProps<T>, C>(\n    WrappedComponent: React.ComponentType<T>\n  ) {\n    type Props = React.JSX.LibraryManagedAttributes<C, Omit<P, \"data\">>;\n    // Creating the inner component. The calculated Props type here is the where the magic happens.\n    return class ComponentWithTheme extends React.Component<Props> {\n      public render() {\n        // Fetch the props you want inject. This could be done with context instead.\n        const mappedStateProps = mapStateToProps(this.state, this.props);\n        const mappedDispatchProps = mapDispatchToProps(this.state, this.props);\n        // this.props comes afterwards so the can override the default ones.\n        return (\n          <WrappedComponent\n            {...this.props}\n            {...mappedStateProps}\n            {...mappedDispatchProps}\n          />\n        );\n      }\n    };\n  };\n}\n```\n\n[View in TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtCAOwGd5qQQkaY64BeOAbQF0A3BSq0GcAMK4WbADLAx3ABQBKLgD44iinDgAeACbAAbnAD0aisuHlq9RlNYwAykgA2SDNC6aA+gC44FBoATwAaOAgAdxoABRwwOgCg4NVODUUAb204YH0AqNj4ugA6XIoAX2UhG1F7ZkcAQQxgUW8VdU0s8h0UfX1JerYAxQYoANHgGgBzVI0maXZisABXOgALTLgYJAAPGHGYKHDcgPnHEvdpmDW4Soqq61sxSRoaD23+hzZvWzeMLW6cDObBc7k8R2ywJgTRgLXolkUAwWcgYD0o5FMpi2ayQdCQgSI2PxYCKWwgcAARvjJgArd5IfSU4JEuAACQA8uIKJNtlBMOh8QB1YDXJzLCl0NBQYBgWG0OIQBK6AAqGi6On0KBgKACyuq5QomGWNGatCBtD+MEUIBQYCc2u2yogCoSAQAYsbTTRwjawAAReRgLVoNZOl2JOAek1ymiqdVwIgwZZQGhwI3RuEq8IxOC7bY0fQcYWi8WS6WyuHhlVqcLiNQAnQ6QVQW1gBkDSBvIaIYgwYod2iOZXBNvV7Jx7I6GAj-Hh7wAKScAA1inIKS2oMEALJBFBTBkNGCHYAU5bbOi6cThdkgEW6GLhABEmu1j7UamqjbMWPERC1kymFlJjeKBzXAQc2GKOBlRxIEUFcNBllcLUGTgOdpzbOAcUJeQWUibD8WufEbSmYA0Cw1tWBKScEyQJMUyBZC6A4AcuxgYtQxxFhcz2VhCx7dA+1Yxx7yKNUaJ0FYKVcMjaILJAoHaeMvx0TFIzokMWRJRUOGCCBljgSIgngWl3igmDcOoJDGSpOB9EHQyRRuWxtj2HI7FQfRigkxsnngX0230e0ULnbhfWCx1nSKRRrnkYoGBQ8JYpKbSEjRFTfNqOAAoZAM6CDGAQ1C7LbTygqQzDaLkvih0kCStY4tSuh0oy79sUa0kmFxQJMF5IyoH4uhySIuDUwgIwFOlfRCNg6b+SQ+BB2owEMsTZNUwbVqdF0ZtKM+cC2J8jKMmKU7qqag0Vq2uATtOnKgtq8NLuuxtbuKe6yuDNYnqOxtzF+lqv2extyk-W59SAA)\n\n## Docs Example: [Wrap the Display Name for Easy Debugging](https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging)\n\nThis is pretty straightforward as well.\n\n```tsx\ninterface WithSubscriptionProps {\n  data: any;\n}\n\nfunction withSubscription<\n  T extends WithSubscriptionProps = WithSubscriptionProps\n>(WrappedComponent: React.ComponentType<T>) {\n  class WithSubscription extends React.Component {\n    /* ... */\n    public static displayName = `WithSubscription(${getDisplayName(\n      WrappedComponent\n    )})`;\n  }\n  return WithSubscription;\n}\n\nfunction getDisplayName<T>(WrappedComponent: React.ComponentType<T>) {\n  return WrappedComponent.displayName || WrappedComponent.name || \"Component\";\n}\n```\n\n## Unwritten: [Caveats section](https://reactjs.org/docs/higher-order-components.html#caveats)\n\n- Don’t Use HOCs Inside the render Method\n- Static Methods Must Be Copied Over\n- Refs Aren’t Passed Through\n"
  },
  {
    "path": "docs/migration/from-flow.md",
    "content": "---\nid: from_flow\ntitle: From Flow\n---\n\n- (2022) Try Stripe's [Flow to TS codemod](https://github.com/stripe-archive/flow-to-typescript-codemod): [blogpost](https://stripe.com/blog/migrating-to-typescript), [podcast discussion](https://devtools.fm/episode/33)\n- Try flow2ts: `npx flow2ts` - doesn't work 100% but saves some time ([see this and other tips from @braposo](https://github.com/typescript-cheatsheets/react/pull/79#issuecomment-458227322) at TravelRepublic)\n- Try [Airtable's codemod](https://github.com/Airtable/typescript-migration-codemod): https://medium.com/airtable-eng/the-continual-evolution-of-airtables-codebase-migrating-a-million-lines-of-code-to-typescript-612c008baf5c\n- [Incremental Migration to TypeScript on a Flowtype codebase][entria] at Entria\n- [MemSQL's Studio's migration](https://davidgom.es/porting-30k-lines-of-code-from-flow-to-typescript/) - blogpost with many useful tips\n- Quick-n-dirty [Flow to TS Codemod](https://gist.github.com/skovhus/c57367ce6ecbc3f70bb7c80f25727a11)\n- [Ecobee's brief experience](https://mobile.twitter.com/alanhietala/status/1104450494754377728)\n- [Migrating a 50K SLOC Flow + React Native app to TypeScript](https://blog.usejournal.com/migrating-a-flow-react-native-app-to-typescript-c74c7bceae7d)\n- [How we migrated 400K+ lines of code from Flow to TypeScript at Factorial](https://labs.factorialhr.com/posts/how-we-migrated-400k-lines-of-code-from-flow-to-typescript)\n  [entria]: https://medium.com/entria/incremental-migration-to-typescript-on-a-flowtype-codebase-515f6490d92d \"Incremental Migration to TypeScript on a Flowtype codebase\"\n"
  },
  {
    "path": "docs/migration/from-js.md",
    "content": "---\nid: from_js\ntitle: From JS\n---\n\n## Automated JS to TS Conversion\n\n- [TypeStat](https://github.com/JoshuaKGoldberg/TypeStat) ([used by Codecademy](https://mobile.twitter.com/JoshuaKGoldberg/status/1159090281314160640))\n- [TypeWiz](https://github.com/urish/typewiz)\n- [js-to-ts-converter](https://github.com/gregjacobs/js-to-ts-converter)\n- [TS-migrate](https://github.com/airbnb/ts-migrate) used in [Airbnb's conversion](https://medium.com/airbnb-engineering/ts-migrate-a-tool-for-migrating-to-typescript-at-scale-cd23bfeb5cc)\n- [dts-gen](https://github.com/microsoft/dts-gen) - `dts-gen` is a tool that generates TypeScript definition files (.d.ts) from any JavaScript object.\n\nfor JSON - http://json2ts.com/ generate TypeScript interfaces from JSON\n\n## Manual JS to TS Conversion\n\nthe \"Just Renaming\" strategy\n\n- OSX/Linux: `find src -name \"*.js\" -exec sh -c 'mv \"$0\" \"${0%.js}.tsx\"' {} \\;`\n\nYou can either load typescript files with webpack, or use the `tsc` compiler to compile your TS files to JS side by side. The basic `tsconfig.json` is:\n\n```json\n{\n  \"compilerOptions\": {\n    \"allowJs\": true\n  }\n}\n```\n\nThen you will want to enable it to check JS:\n\n```json\n{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"checkJs\": true\n  }\n}\n```\n\nIf you have a large codebase and this throws too many errors at once, you can opt out problematic files with `//@ts-nocheck`, or instead turn off `checkJs` and add a `//@ts-check` directive at the top of each regular JS file.\n\nTypeScript should throw up some egregious errors here which should be easy to fix.\n\nOnce you are done, swallow the red pill by turning off implicit `any`'s:\n\n```js\n{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"noImplicitAny\": true // or \"strict\": true\n  }\n}\n```\n\nThis will raise a bunch of type errors and you can start converting files to TS or (optionally) use [JSDoc annotations](https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html) in your JS.\n\nA common practice here is using an ambient TODO type alias for `any` so you can keep track of what you need to come back to:\n\n```ts\ntype TODO_TYPEME = any;\nexport function myFunc(foo: TODO_TYPEME, bar: TODO_TYPEME): number {\n  // ...\n}\n```\n\nGradually add [more `strict` mode flags](https://www.typescriptlang.org/docs/handbook/compiler-options.html) like `noImplicitThis`, `strictNullChecks`, and so on until you can eventually just run in full strict mode with no js files left:\n\n```js\n{\n  \"compilerOptions\": {\n    \"strict\": true\n  }\n}\n```\n\n## 3 Step Process\n\n![image](https://user-images.githubusercontent.com/6764957/91499410-f1399080-e8f3-11ea-86f8-431266af713b.png)\n\nhttps://speakerdeck.com/amhinson/convert-a-react-native-project-to-typescript-in-10-minutes?slide=23\n\n## More resources\n\n- [Adopting TypeScript at Scale - AirBnB's conversion story and strategy](https://www.youtube.com/watch?v=P-J9Eg7hJwE) - their [ts-migrate tool here](https://medium.com/airbnb-engineering/ts-migrate-a-tool-for-migrating-to-typescript-at-scale-cd23bfeb5cc)\n- [Scaling TypeScript lessons from Bloomberg](https://www.techatbloomberg.com/blog/10-insights-adopting-typescript-at-scale/)\n- [Migrating a `create-react-app`/`react-scripts` app to TypeScript](https://facebook.github.io/create-react-app/docs/adding-typescript) - don't use `react-scripts-ts`\n- [Migrating an EJECTED CRA app to TS](https://spin.atomicobject.com/2018/07/04/migrating-cra-typescript/)\n- [Lyft's JS to TS migration tool](https://github.com/lyft/react-javascript-to-typescript-transform) (includes PropTypes migration)\n- [Hootsuite][hootsuite]\n- [Etsy's Journey to TypeScript](https://codeascraft.com/2021/11/08/etsys-journey-to-typescript/)\n- [Storybook's migration (PR)](https://github.com/storybooks/storybook/issues/5030)\n- [How we migrated a 200K+ LOC project to TypeScript and survived to tell the story][coherentlabs] - Coherent Labs - using `grunt-ts`, jQuery and Kendo UI\n- incrementally adding strict null checks https://code.visualstudio.com/blogs/2019/05/23/strict-null\n\nOld content that is possibly out of date\n\n- [Incrementally Migrating JS to TS][clayallsop] (old)\n- [Microsoft's TypeScript React Conversion Guide][mstsreactconversionguide] (old)\n\n[clayallsop]: https://medium.com/@clayallsopp/incrementally-migrating-javascript-to-typescript-565020e49c88 \"Incrementally Migrating JavaScript to TypeScript\"\n[pleo]: https://medium.com/pleo/migrating-a-babel-project-to-typescript-af6cd0b451f4 \"Migrating a Babel project to TypeScript\"\n[tiny]: https://go.tiny.cloud/blog/benefits-of-gradual-strong-typing-in-javascript/ \"Benefits of gradual strong typing in JavaScript\"\n[entria]: https://medium.com/entria/incremental-migration-to-typescript-on-a-flowtype-codebase-515f6490d92d \"Incremental Migration to TypeScript on a Flowtype codebase\"\n[mstsreactconversionguide]: https://github.com/Microsoft/TypeScript-React-Conversion-Guide \"TypeScript React Conversion Guide\"\n[coherentlabs]: https://hashnode.com/post/how-we-migrated-a-200k-loc-project-to-typescript-and-survived-to-tell-the-story-ciyzhikcc0001y253w00n11yb \"How we migrated a 200K+ LOC project to TypeScript and survived to tell the story\"\n[hootsuite]: https://medium.com/hootsuite-engineering/thoughts-on-migrating-to-typescript-5e1a04288202 \"Thoughts on migrating to TypeScript\"\n"
  },
  {
    "path": "docs/migration/index.md",
    "content": "---\nid: intro\nsidebar_label: Intro\ntitle: Migrating (to TypeScript) Cheatsheet\n---\n\nThis Cheatsheet collates advice and utilities from real case studies of teams moving significant codebases from plain JS or Flow over to TypeScript. It makes no attempt to _convince_ people to do so, but we do collect what few statistics companies offer up after their conversion experience.\n\n> ⚠️ This Cheatsheet is extremely new and could use all the help we can get. Solid advice, results, and up to date content all welcome.\n\n## Prerequisite\n\nRead [TypeScript's official Guide for migrating from JS](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html) and you should already be familiar with their [React conversion guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide).\n\n## General Conversion approaches\n\n- Level 0: Don't use TypeScript, use JSDoc\n  - See our [JSDoc section](./js-docs.md)\n- Level 1A: Majority JavaScript, increasingly strict TypeScript\n  - as recommended by [official TS guide](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html)\n  - use `allowJS` (Experiences: [clayallsop][clayallsop], [pleo][pleo])\n- Level 1B: Total rename to TypeScript from the start\n  - \"[Just rename all .js files to .ts](https://twitter.com/jamonholmgren/status/1089241726303199232)\"?\n  - use the loosest, bare minimum settings to start with\n- Level 2: Strict TypeScript\n  - use Microsoft's [`dts-gen`](https://github.com/microsoft/DefinitelyTyped-tools/tree/main/packages/dts-gen) to generate `.d.ts` files for your untyped files. [This SO answer](https://stackoverflow.com/questions/12687779/how-do-you-produce-a-d-ts-typings-definition-file-from-an-existing-javascript) has more on the topic.\n  - use `declare` keyword for ambient declarations - see [declaration merging](https://github.com/typescript-cheatsheets/react#troubleshooting-handbook-bugs-in-official-typings) to patch library declarations inline\n\nMisc tips/approaches successful companies have taken\n\n- `@ts-expect-error` on compiler errors for libraries with no typedefs\n- pick ESLint over TSLint (source: [ESLint](https://eslint.org/blog/2019/01/future-typescript-eslint) and [TS Roadmap](https://github.com/Microsoft/TypeScript/issues/29288)). [You can convert TSlint to ESlint with this tool](https://github.com/typescript-eslint/tslint-to-eslint-config).\n- New code must always be written in TypeScript. No exceptions. For existing code: If your task requires you to change JavaScript code, you need to rewrite it. (Source: [Hootsuite][hootsuite])\n\n<details>\n<summary>\n<b>\nWebpack tips\n</b>\n</summary>\n\n- webpack loader: `awesome-typescript-loader` vs `ts-loader`? (there is some disagreement in community about this - but read [awesome's point of view](https://github.com/s-panferov/awesome-typescript-loader#differences-between-ts-loader))\n- Webpack config:\n\n```js\nmodule.exports = {\n\nresolve: {\n-    extensions: ['.js', '.jsx']\n+    extensions: ['.ts', '.tsx', '.js', '.jsx']\n},\n\n// Source maps support ('inline-source-map' also works)\ndevtool: 'source-map',\n\n// Add the loader for .ts files.\nmodule: {\n  loaders: [{\n-       test: /\\.jsx?$/,\n-       loader: 'babel-loader',\n-       exclude: [/node_modules/],\n+       test: /\\.(t|j)sx?$/,\n+       loader: ['awesome-typescript-loader?module=es6'],\n+       exclude: [/node_modules/]\n+   }, {\n+       test: /\\.js$/,\n+       loader: 'source-map-loader',\n+       enforce: 'pre'\n  }]\n}\n};\n```\n\nSpecial note on `ts-loader` and 3rd party libraries: https://twitter.com/acemarke/status/1091150384184229888\n\n</details>\n\n## Academic Studies of Migration\n\n> Note: Empirical Software Engineering is desirable, but [extremely hard](https://hillelwayne.com/talks/what-we-know-we-dont-know/). Please be gentle but also please share if you find quality research!\n\n- [To Type or Not to Type: Quantifying Detectable Bugs in JavaScript](http://earlbarr.com/publications/typestudy.pdf)\n\n> Our central finding is that both static type systems find an important percentage of public bugs: both Flow 0.30 and TypeScript 2.0 successfully detect 15%!\n\n- [Empirical study on the impact of static typing](https://www.researchgate.net/publication/259634489_An_empirical_study_on_the_impact_of_static_typing_on_software_maintainability)\n\nsee also [Things I was Wrong About: Types](https://v5.chriskrycho.com/journal/things-i-was-wrong-about/1-types/) and [A Large Scale Study of Programming Languages\nand Code Quality in GitHub](https://web.cs.ucdavis.edu/~filkov/papers/lang_github.pdf)\n\n## Misc migration stories by notable companies and open source\n\n- (2022) Stripe: https://stripe.com/blog/migrating-to-typescript ([podcast](https://devtools.fm/episode/33), [tweet](https://twitter.com/alunny/status/1501261144341680130))\n- [Bloomberg](https://www.techatbloomberg.com/blog/10-insights-adopting-typescript-at-scale/) - [Podcast form](https://talkscript.sitepen.com/episode-57-typescript-at-scale/)\n- [Adopting TypeScript at Scale - AirBnB's conversion story and strategy](https://www.youtube.com/watch?v=P-J9Eg7hJwE)\n- Airtable's [Big Bang Migration from Flow to TS](https://medium.com/airtable-eng/the-continual-evolution-of-airtables-codebase-migrating-a-million-lines-of-code-to-typescript-612c008baf5c)\n- [Lyft](https://eng.lyft.com/typescript-at-lyft-64f0702346ea)\n- [Google](http://neugierig.org/software/blog/2018/09/typescript-at-google.html)\n- [Tiny][tiny] - [Talk from ForwardJS here](https://www.slideshare.net/tiny/porting-100k-lines-of-code-to-typescript)\n- [Slack](https://slack.engineering/typescript-at-slack-a81307fa288d) ([podcast](https://softwareengineeringdaily.com/2017/08/11/typescript-at-slack-with-felix-rieseberg/))\n- [Etsy](https://codeascraft.com/2021/11/08/etsys-journey-to-typescript/)\n- [Netflix adoption story](https://www.youtube.com/watch?v=p5Hwb1YbNMY&feature=share)\n- [Priceline](https://medium.com/priceline-labs/trying-out-typescript-part-1-15a5267215b9)\n- Dropbox\n  - [Talk at React Loop](https://www.youtube.com/watch?v=veXkJq0Z2Qk)\n  - [Blogpost: The Great CoffeeScript to TypeScript Migration of 2017](https://dropbox.tech/frontend/the-great-coffeescript-to-typescript-migration-of-2017)\n- [Heap - How we failed, then succeeded, at migrating to TypeScript](https://heap.io/blog/migrating-to-typescript)\n- Execute Program (Gary Bernhardt) https://www.executeprogram.com/blog/porting-to-typescript-solved-our-api-woes\n\nOpen Source\n\n- [Jest's migration (PR)](https://github.com/facebook/jest/pull/7554#issuecomment-454358729)\n- [Expo's migration (issue)](https://github.com/expo/expo/issues/2164)\n- [Google Workbox migration](https://github.com/GoogleChrome/workbox/pull/2058)\n- [Chrome Dev Tools related issues](https://twitter.com/TimvdLippe/status/1220393069792694281)\n- [Atlassian's migration (PR)](https://github.com/atlassian/react-beautiful-dnd/issues/982)\n- [Yarn's migration (issue)](https://github.com/yarnpkg/yarn/issues/6953)\n- [React Native CLI](https://github.com/react-native-community/cli/issues/683)\n- [Next.js](https://nextjs.org/blog/next-9)\n- React Router\n  - [v5 attempt](https://github.com/ReactTraining/react-router/issues/6955)\n  - [React Router v6](https://github.com/ReactTraining/react-router/releases/tag/v6.0.0-alpha.4)\n  - [history](https://github.com/ReactTraining/history/pull/774) - [final](https://github.com/ReactTraining/history/commit/1e91a64a858604062d804e4d51eb1d2a020a95c8)\n- [Docusaurus v2](https://github.com/facebook/docusaurus/pull/2578)\n- [Gatsby](https://github.com/gatsbyjs/gatsby/issues/21995)\n- [Redux](https://github.com/reduxjs/redux/pull/3536)\n- [Theme-UI](https://github.com/system-ui/theme-ui/issues/668)\n- [Hasura Console](https://github.com/hasura/graphql-engine/issues/4314)\n- [Storybook](https://github.com/storybookjs/storybook/pulls?page=4&q=is%3Apr+sort%3Aupdated-desc+is%3Aclosed+typescript+label%3Atypescript)\n- [Dojo 1 -> 2 migration](https://topenddevs.com/podcasts/javascript-jabber/episodes/jsj-277-dojo-2-with-dylan-schiemann-and-kitson-kelly)\n\n## Migration Results\n\n- Number of production deploys doubled for [Hootsuite][hootsuite]\n- Found accidental globals for [Tiny][tiny]\n- Found incorrect function calls for [Tiny][tiny]\n- Found rarely used, buggy code that was untested for [Tiny][tiny]\n\n[clayallsop]: https://medium.com/@clayallsopp/incrementally-migrating-javascript-to-typescript-565020e49c88 \"Incrementally Migrating JavaScript to TypeScript\"\n[pleo]: https://medium.com/pleo/migrating-a-babel-project-to-typescript-af6cd0b451f4 \"Migrating a Babel project to TypeScript\"\n[tiny]: https://go.tiny.cloud/blog/benefits-of-gradual-strong-typing-in-javascript/ \"Benefits of gradual strong typing in JavaScript\"\n[entria]: https://medium.com/entria/incremental-migration-to-typescript-on-a-flowtype-codebase-515f6490d92d \"Incremental Migration to TypeScript on a Flowtype codebase\"\n[mstsreactconversionguide]: https://github.com/Microsoft/TypeScript-React-Conversion-Guide \"TypeScript React Conversion Guide\"\n[coherentlabs]: https://hashnode.com/post/how-we-migrated-a-200k-loc-project-to-typescript-and-survived-to-tell-the-story-ciyzhikcc0001y253w00n11yb \"How we migrated a 200K+ LOC project to TypeScript and survived to tell the story\"\n[hootsuite]: https://medium.com/hootsuite-engineering/thoughts-on-migrating-to-typescript-5e1a04288202 \"Thoughts on migrating to TypeScript\"\n"
  },
  {
    "path": "docs/migration/js-docs.md",
    "content": "---\nid: js_docs\ntitle: JSDoc\n---\n\n- https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript\n- webpack's codebase uses JSDoc with linting by TS https://twitter.com/TheLarkInn/status/984479953927327744 (some crazy hack: https://twitter.com/thelarkinn/status/996475530944823296)\n- JSDoc can type check if using closure-compiler https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System\n\nProblems to be aware of:\n\n- `object` is converted to `any` for some reason.\n- If you have an error in the jsdoc, you get no warning/error. TS just silently doesn't type annotate the function.\n- [casting can be verbose](https://twitter.com/bahmutov/status/1089229349637754880)\n\n(_thanks [Gil Tayar](https://twitter.com/giltayar/status/1089228919260221441) and [Gleb Bahmutov](https://twitter.com/bahmutov/status/1089229196247908353) for sharing above commentary_)\n"
  },
  {
    "path": "docs/react-types/ComponentProps.md",
    "content": "---\ntitle: ComponentProps<ElementType>\n---\n\n`ComponentProps<ElementType>` constructs a type with all valid props of an element or inferred props of a component. It's an alias for `ComponentPropsWithRef<ElementType>`.\n\n:::note\n**React 19+**: `ComponentPropsWithRef<ElementType>` is recommended as refs are now passed as props in function components. (See [forwardRef/createRef](/docs/basic/getting-started/forward_and_create_ref))\n\n**React ≤18**: Prefer `ComponentPropsWithRef<ElementType>` if ref is forwarded and `ComponentPropsWithoutRef<ElementType>` when ref is not forwarded.\n:::\n\n## Parameters\n\n- `ElementType`: An element type. Examples include:\n  - An HTML or SVG element string literal such as `\"div\"`, `\"h1\"` or `\"path\"`.\n  - A component type, such as `typeof Component`.\n\n## Usage\n\n### Get all valid props of an element\n\n`ComponentProps<ElementType>` can be used to create a type that includes all valid `div` props.\n\n```tsx\ninterface Props extends ComponentProps<\"div\"> {\n  text: string;\n}\n\nfunction Component({ className, children, text, ...props }: Props) {\n  // `props` includes `text` in addition to all valid `div` props\n}\n```\n\n### Infer component props type\n\nIn some cases, you might want to infer the type of a component's props.\n\n```tsx\ninterface Props {\n  text: string;\n}\n\nfunction Component(props: Props) {\n  // ...\n}\n\ntype MyType = ComponentProps<typeof Component>;\n//     ^? type MyType = Props\n```\n\n#### Infer specific prop type\n\nThe type of a specific prop can also be inferred this way. Let's say you are using an `<Icon>` component from a component library. The component takes a `name` prop that determines what icon is shown. You need to use the type of `name` in your app, but it's not made available by the library. You could create a custom type:\n\n```tsx\ntype IconName = \"warning\" | \"checkmark\";\n```\n\nHowever, this type is not really reflecting the actual set of icons made available by the library. A better solution is to infer the type:\n\n```tsx\nimport { Icon } from \"component-library\";\n\ntype IconName = ComponentProps<typeof Icon>[\"name\"];\n//       ^? type IconName = \"warning\" | \"checkmark\"\n```\n\nYou can also use the `Pick<Type, Keys>` utility type to accomplish the same thing:\n\n```tsx\nimport { Icon } from \"component-library\";\n\ntype IconName = Pick<ComponentProps<typeof Icon>, \"name\">;\n//       ^? type IconName = \"warning\" | \"checkmark\"\n```\n"
  },
  {
    "path": "docs/react-types/ReactNode.md",
    "content": "---\ntitle: ReactNode\n---\n\n`ReactNode` is a type that describes what React can render.\n\n## Parameters\n\n`ReactNode` does not take any parameters.\n\n## Usage\n\n### Typing `children`\n\nThe most common use case for `ReactNode` is typing `children`.\n\n```tsx\nimport { ReactNode } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n}\n\nfunction Component({ children }: Props) {\n  return children;\n}\n```\n\n`<Component>` accepts anything that React can render as `children`. Here are some examples:\n\n```tsx\nfunction Examples() {\n  return (\n    <>\n      <Component>\n        <div>Hello</div>\n      </Component>\n      <Component>Hello</Component>\n      <Component>{123}</Component>\n      <Component>\n        <>Hello</>\n      </Component>\n      <Component>{true}</Component>\n      <Component>{null}</Component>\n      <Component>{undefined}</Component>\n      <Component>{[1, 2, 3]}</Component>\n    </>\n  );\n}\n```\n"
  },
  {
    "path": "docs/react-types/index.md",
    "content": "---\ntitle: React Types\n---\n\n`@types/react` makes some types available that can be very useful. Here's a list in alphabetical order with links to the detailed reference pages.\n\n- [`ComponentProps<ElementType>`](/docs/react-types/ComponentProps)\n- [`ReactNode`](/docs/react-types/ReactNode)\n"
  },
  {
    "path": "genReadme.js",
    "content": "const fs = require(\"fs/promises\");\nconst path = require(\"path\");\nconst Fm = require(\"front-matter\");\nconst Toc = require(\"markdown-toc\");\nconst prettier = require(\"prettier\");\nconst yargs = require(\"yargs/yargs\");\nconst { hideBin } = require(\"yargs/helpers\");\n\nconst repositoryRootPath = __dirname;\nconst readmePath = path.resolve(repositoryRootPath, \"./README.md\");\n/**\n * level of the heading under which the generated content is displayed\n */\nconst baseHeadingLevel = 2;\nconst defaultOptions = {\n  withKey: \"title\",\n  withToc: false,\n  showHeading: true,\n  relativeHeadingLevel: 2,\n  tabLevel: 1,\n  prefix: \"\",\n  suffix: \"\",\n};\n\nasync function readContentFromPath(relativePath) {\n  let MdDoc = await fs.readFile(path.join(repositoryRootPath, relativePath), {\n    encoding: \"utf8\",\n  });\n  let MdContent = Fm(MdDoc.toString());\n  let TableOfContents = Toc(MdContent.body).content;\n  return {\n    frontmatter: MdContent.attributes,\n    body: MdContent.body,\n    toc: TableOfContents,\n  };\n}\n\nasync function updateSectionWith(options) {\n  const {\n    from,\n    relativeHeadingLevel,\n    name,\n    path,\n    prefix,\n    showHeading,\n    suffix,\n    tabLevel,\n    to,\n    withKey,\n    withToc,\n  } = { ...defaultOptions, ...options };\n  let md = await readContentFromPath(path);\n  let oldFences = getFenceForSection(from, name);\n  let fenceOptions = {\n    name,\n    content: md,\n    tabLevel,\n    relativeHeadingLevel,\n    showHeading,\n    withKey,\n    prefix,\n    suffix,\n  };\n  let newFences = generateContentForSection({\n    ...fenceOptions,\n    withToc: false,\n  });\n  let oldTocFences = getFenceForSection(from, name, true);\n  let newTocFences = generateContentForSection({\n    ...fenceOptions,\n    withToc: true,\n  });\n  let updatedContents = to.replace(oldFences.regex, newFences);\n  updatedContents = updatedContents.replace(oldTocFences.regex, newTocFences);\n  if (withToc)\n    console.log(\n      `✅ 🗜️ Rewrote Table of Contents for '${md.frontmatter.title}'`\n    );\n  console.log(`✅ 📝 Rewrote Section for '${md.frontmatter.title}'`);\n  return updatedContents;\n}\n\n/**\n * Adjusts the headings in the given `markdown` to be in a given heading context.\n * Headings must start in a line.\n * Preceding whitespace or any other character will result in the heading not being recognized.\n *\n * @example `withHeadingContext(2, '# Heading') === '### Heading'`\n * @param {number} relativeHeadingLevel\n * @param {string} markdown\n */\nfunction withHeadingContext(relativeHeadingLevel, markdown) {\n  return markdown.replaceAll(/^(#+)/gm, (match, markdownHeadingTokens) => {\n    return \"#\".repeat(markdownHeadingTokens.length + relativeHeadingLevel);\n  });\n}\n\nfunction generateContentForSection(options) {\n  const {\n    content,\n    relativeHeadingLevel,\n    name,\n    prefix,\n    showHeading,\n    suffix,\n    tabLevel,\n    withKey,\n    withToc,\n  } = {\n    ...defaultOptions,\n    ...options,\n  };\n  let fence = getFence(name, withToc);\n  let fenceContent = fence.start + \"\\n\";\n  if (withToc) {\n    let lines = content.toc.split(\"\\n\");\n    for (let i = 0, len = lines.length; i < len; i += 1)\n      fenceContent +=\n        \"  \".repeat(tabLevel) + lines[i] + (i !== len - 1 ? \"\\n\" : \"\");\n  } else {\n    fenceContent += showHeading\n      ? `${\"#\".repeat(baseHeadingLevel + relativeHeadingLevel)} ` +\n        prefix +\n        content.frontmatter[withKey] +\n        suffix +\n        \"\\n\\n\"\n      : \"\";\n    fenceContent += withHeadingContext(baseHeadingLevel, content.body) + \"\\n\";\n  }\n  fenceContent += fence.end;\n  return fenceContent;\n}\nfunction getFenceForSection(readme, sectionName, isToc = false) {\n  try {\n    let fence = getFence(sectionName, isToc);\n    let regex = new RegExp(`(${fence.start}[\\\\s\\\\S]+${fence.end})`, \"gm\");\n    return { regex: regex, content: regex.exec(readme.content) };\n  } catch (err) {\n    console.error(\n      `🚨 You've encountered a ${err.name} ➜ ${err.message} \\n` +\n        `💡 ProTip ➜ Please ensure the comments exist and are separated by a newline.`\n    );\n\n    console.error({ readme, sectionName });\n    console.error(err);\n  }\n}\nfunction getFence(sectionName, isToc = false) {\n  let name = isToc ? sectionName + \"-toc\" : sectionName;\n  let START_COMMENT = \"<!--START-SECTION:\" + name + \"-->\";\n  let END_COMMENT = \"<!--END-SECTION:\" + name + \"-->\";\n  return { start: START_COMMENT, end: END_COMMENT };\n}\n\nasync function main(argv) {\n  let currentReadme = await fs.readFile(readmePath, { encoding: \"utf-8\" });\n\n  let pendingReadme = currentReadme;\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"setup\",\n    path: \"docs/basic/setup.md\",\n    withToc: true,\n    relativeHeadingLevel: 1,\n    prefix: \"Section 1: \",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"basic-type-examples\",\n    path: \"docs/basic/getting-started/basic-type-examples.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"function-components\",\n    path: \"docs/basic/getting-started/function-components.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"hooks\",\n    path: \"docs/basic/getting-started/hooks.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"class-components\",\n    path: \"docs/basic/getting-started/class-components.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"default-props\",\n    path: \"docs/basic/getting-started/default-props.md\",\n    showHeading: false,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"forms-and-events\",\n    path: \"docs/basic/getting-started/forms-and-events.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"context\",\n    path: \"docs/basic/getting-started/context.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"forward-create-ref\",\n    path: \"docs/basic/getting-started/forward-create-ref.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"portals\",\n    path: \"docs/basic/getting-started/portals.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"error-boundaries\",\n    path: \"docs/basic/getting-started/error-boundaries.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"concurrent\",\n    path: \"docs/basic/getting-started/concurrent.md\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"types\",\n    path: \"docs/basic/troubleshooting/types.md\",\n    withToc: true,\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"operators\",\n    path: \"docs/basic/troubleshooting/operators.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"utilities\",\n    path: \"docs/basic/troubleshooting/utilities.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"ts-config\",\n    path: \"docs/basic/troubleshooting/ts-config.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"official-typings-bugs\",\n    path: \"docs/basic/troubleshooting/official-typings-bugs.md\",\n    relativeHeadingLevel: 1,\n    withKey: \"sidebar_label\",\n    prefix: \"Troubleshooting Handbook: \",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"non-ts-files\",\n    path: \"docs/basic/troubleshooting/non-ts-files.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"non-ts-files\",\n    path: \"docs/basic/troubleshooting/non-ts-files.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"editor-integration\",\n    path: \"docs/basic/editor-integration.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"linting\",\n    path: \"docs/basic/linting.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"resources\",\n    path: \"docs/basic/recommended/resources.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"talks\",\n    path: \"docs/basic/recommended/talks.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"codebases\",\n    path: \"docs/basic/recommended/codebases.md\",\n    relativeHeadingLevel: 1,\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"learn-ts\",\n    path: \"docs/basic/troubleshooting/learn-ts.md\",\n    relativeHeadingLevel: 1,\n    withKey: \"sidebar_label\",\n  });\n  pendingReadme = await updateSectionWith({\n    from: currentReadme,\n    to: pendingReadme,\n    name: \"examples\",\n    path: \"docs/basic/examples.md\",\n    relativeHeadingLevel: 1,\n  });\n\n  const prettierConfig = await prettier.resolveConfig(readmePath);\n  pendingReadme = prettier.format(pendingReadme, {\n    ...prettierConfig,\n    filepath: path.basename(readmePath),\n  });\n\n  await fs.writeFile(readmePath, pendingReadme);\n}\n\nyargs(hideBin(process.argv))\n  .command({\n    command: \"$0\",\n    describe: \"Generate the README.md from docs/ folder\",\n    handler: main,\n  })\n  .usage(\"node $0 [args]\")\n  .help()\n  .strict()\n  .parse();\n"
  },
  {
    "path": "netlify.toml",
    "content": "[build]\n  # Directory to change to before starting a build.\n  # This is where we will look for package.json/.nvmrc/etc.\n  base = \"website\"\n\n  # otherwise netlify keeps ignoring changes in /docs\n  ignore = \"/bin/false\"\n\n  # Directory (relative to root of your repo) that contains the deploy-ready\n  # HTML files and assets generated by the build. If a base directory has\n  # been specified, include it in the publish directory path.\n  publish = \"build\"\n\n  # Default build command.\n  command = \"yarn build\"\n\n  # Directory with the serverless Lambda functions to deploy to AWS.\n  # functions = \"project/functions/\"\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"react-typescript-cheatsheet\",\n  \"version\": \"1.0.0\",\n  \"description\": \"this package.json is just for maintenance work\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/typescript-cheatsheets/react.git\"\n  },\n  \"keywords\": [\n    \"react\",\n    \"typescript\",\n    \"guides\"\n  ],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"bugs\": {\n    \"url\": \"https://github.com/typescript-cheatsheets/react/issues\"\n  },\n  \"homepage\": \"https://github.com/typescript-cheatsheets/react#readme\",\n  \"scripts\": {\n    \"format-readme\": \"prettier --write \\\"README.md\\\"\",\n    \"gen-readme\": \"node genReadme.js\",\n    \"format\": \"prettier --write \\\"**/*.md\\\"\",\n    \"format:check\": \"prettier --check \\\"**/*.md\\\"\",\n    \"postinstall\": \"cd website && yarn\",\n    \"prepare\": \"husky install\",\n    \"start\": \"yarn --cwd website start\",\n    \"build\": \"yarn --cwd website build\"\n  },\n  \"dependencies\": {\n    \"front-matter\": \"^4.0.2\",\n    \"markdown-toc\": \"^1.2.0\",\n    \"yargs\": \"^17.5.1\"\n  },\n  \"devDependencies\": {\n    \"husky\": \"^7.0.0\",\n    \"prettier\": \"^2.6.2\",\n    \"pretty-quick\": \"^3.1.3\"\n  }\n}\n"
  },
  {
    "path": "website/README.md",
    "content": "# Website\n\nThis website is built using [Docusaurus 2](https://v2.docusaurus.io/), a modern static website generator.\n\n### Installation\n\n```\n$ yarn\n```\n\n### Local Development\n\n```\n$ yarn start\n```\n\nThis command starts a local development server and open up a browser window. Most changes are reflected live without having to restart the server.\n\n### Build\n\n```\n$ yarn build\n```\n\nThis command generates static content into the `build` directory and can be served using any static contents hosting service.\n\n### Deployment\n\n```\n$ GIT_USER=<Your GitHub username> USE_SSH=true yarn deploy\n```\n\nIf you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.\n"
  },
  {
    "path": "website/docusaurus.config.js",
    "content": "const { themes } = require(\"prism-react-renderer\");\n\n// List of projects/orgs using your project for the users page.\nconst users = [\n  {\n    caption: \"Docusaurus\",\n    image: \"https://docusaurus.io/img/docusaurus.svg\",\n    infoLink: \"https://docusaurus.io/\",\n    pinned: true,\n  },\n];\n\nconst setupDoc = \"docs/basic/setup\";\n\nmodule.exports = {\n  favicon: \"img/icon.png\",\n  title: \"React TypeScript Cheatsheets\", // Title for your website.\n  tagline:\n    \"Cheatsheets for experienced React developers getting started with TypeScript\",\n  url: \"https://react-typescript-cheatsheet.netlify.app\", // Your website URL\n  baseUrl: \"/\",\n  projectName: \"react-typescript-cheatsheet\",\n  organizationName: \"typescript-cheatsheets\",\n\n  presets: [\n    [\n      \"@docusaurus/preset-classic\",\n      {\n        theme: {\n          customCss: require.resolve(\"./src/css/custom.css\"),\n        },\n        docs: {\n          // Docs folder path relative to website dir.\n          path: \"../docs\",\n          // Sidebars file relative to website dir.\n          sidebarPath: require.resolve(\"./sidebars.json\"),\n          editUrl:\n            \"https://github.com/typescript-cheatsheets/react/tree/main/docs\",\n        },\n        // ...\n      },\n    ],\n  ],\n\n  themeConfig: {\n    colorMode: {\n      defaultMode: \"dark\",\n    },\n\n    image:\n      \"https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png\",\n\n    // Equivalent to `docsSideNavCollapsible`.\n    // sidebarCollapsible: false,\n\n    prism: {\n      defaultLanguage: \"typescript\",\n      theme: themes.github,\n      darkTheme: themes.dracula,\n    },\n\n    navbar: {\n      title: \"React TypeScript Cheatsheet\",\n      logo: {\n        alt: \"Logo\",\n        src: \"img/icon.png\",\n      },\n      items: [\n        {\n          to: setupDoc,\n          label: \"Docs\",\n          position: \"right\",\n        },\n        {\n          to: \"help\",\n          label: \"Help\",\n          position: \"right\",\n        },\n        {\n          to: \"https://discord.gg/wTGS5z9\",\n          label: \"Discord\",\n          position: \"right\",\n        },\n        // {to: 'blog', label: 'Blog', position: 'right'},\n      ],\n    },\n\n    footer: {\n      style: \"dark\",\n      logo: {\n        alt: \"TypeScript Cheatsheets Logo\",\n        src: \"img/icon.png\",\n        // maxWidth: 128,\n        // style: { maxWidth: 128, maxHeight: 128 },\n      },\n      copyright: `Copyright © ${new Date().getFullYear()} TypeScript Cheatsheets`,\n      links: [\n        {\n          title: \"Docs\",\n          items: [\n            {\n              label: \"Introduction\",\n              to: setupDoc,\n            },\n            {\n              label: \"High Order Component (HOC)\",\n              to: \"docs/hoc\",\n            },\n            {\n              label: \"Advanced Guides\",\n              to: \"docs/advanced\",\n            },\n            {\n              label: \"Migrating\",\n              to: \"docs/migration\",\n            },\n          ],\n        },\n        {\n          title: \"Community\",\n          items: [\n            {\n              label: \"Stack Overflow\",\n              href: \"https://stackoverflow.com/questions/tagged/typescript\",\n            },\n            {\n              label: \"User Showcase\",\n              to: \"users\",\n            },\n            {\n              label: \"Help\",\n              to: \"help\",\n            },\n            {\n              label: \"Contributors\",\n              to: \"contributors\",\n            },\n            {\n              label: \"Contributing\",\n              to: \"contributing\",\n            },\n          ],\n        },\n        {\n          title: \"More\",\n          items: [\n            {\n              label: \"GitHub\",\n              href: \"https://github.com/typescript-cheatsheets/react\",\n            },\n            {\n              html: `<a class=\"footer__link-item\" href=\"https://github.com/typescript-cheatsheets/react\">\n                <img src=\"https://img.shields.io/github/stars/typescript-cheatsheets/react-typescript-cheatsheet.svg?style=social&amp;label=Star&amp;maxAge=2592000\" alt=\"GitHub stars\" data-canonical-src=\"https://img.shields.io/github/stars/typescript-cheatsheets/react-typescript-cheatsheet.svg?style=social&amp;label=Star&amp;maxAge=2592000\" style=\"max-width:100%;\">\n                </a>`,\n            },\n            {\n              // label: \"Discord\",\n              html: `<a class=\"footer__link-item\" href=\"https://discord.gg/wTGS5z9\">\n              <img src=\"https://img.shields.io/discord/508357248330760243.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2\" style=\"max-width:100%;\" alt=\"Discord\">\n              </a>`,\n            },\n            {\n              // label: \"Spread the word\",\n              html: `<a class=\"footer__link-item\" href=\"http://twitter.com/home?status=Awesome%20%40Reactjs%20%2B%20%40TypeScript%20cheatsheet%20by%20%40ferdaber%2C%20%40sebsilbermann%2C%20%40swyx%20%26%20others!%20https%3A%2F%2Fgithub.com%2Ftypescript-cheatsheets%2Freact\">\n              <img src=\"https://img.shields.io/twitter/url?label=Help%20spread%20the%20word%21&style=social&url=https%3A%2F%2Fgithub.com%2Ftypescript-cheatsheets%2Freact\" style=\"max-width:100%;\" alt=\"X\">\n              </a>`,\n            },\n          ],\n        },\n      ],\n    },\n\n    algolia: {\n      apiKey: \"9a22585d1841d2fa758da919cd08a764\",\n      indexName: \"react-typescript-cheatsheet\",\n      appId: \"J65EL4UPXZ\",\n      algoliaOptions: {\n        //... },\n      },\n    },\n  },\n\n  customFields: {\n    firstDoc: setupDoc,\n\n    // TODO useless user showcase page ?\n    users,\n    addUserUrl:\n      \"https://github.com/typescript-cheatsheets/react/blob/main/website/docusaurus.config.js\",\n  },\n};\n"
  },
  {
    "path": "website/package.json",
    "content": "{\n  \"scripts\": {\n    \"add-pages-on-site\": \"node ../copyFile.js\",\n    \"start\": \"yarn add-pages-on-site && docusaurus start\",\n    \"build\": \"yarn add-pages-on-site && docusaurus build\",\n    \"swizzle\": \"docusaurus swizzle\",\n    \"deploy\": \"yarn add-pages-on-site && docusaurus deploy\"\n  },\n  \"dependencies\": {\n    \"@docusaurus/core\": \"^2.4.0\",\n    \"@docusaurus/preset-classic\": \"^2.4.0\",\n    \"classnames\": \"^2.3.2\",\n    \"prism-react-renderer\": \"^2.4.0\",\n    \"react\": \"^17.0.2\",\n    \"react-dom\": \"^17.0.2\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  }\n}\n"
  },
  {
    "path": "website/sidebars.json",
    "content": "{\n  \"docs\": {\n    \"Basic\": [\n      \"basic/setup\",\n      {\n        \"type\": \"category\",\n        \"label\": \"Getting Started\",\n        \"items\": [\n          \"basic/getting-started/basic_type_example\",\n          \"basic/getting-started/function_components\",\n          \"basic/getting-started/hooks\",\n          \"basic/getting-started/class_components\",\n          \"basic/getting-started/default_props\",\n          \"basic/getting-started/forms_and_events\",\n          \"basic/getting-started/context\",\n          \"basic/getting-started/forward_and_create_ref\",\n          \"basic/getting-started/portals\",\n          \"basic/getting-started/error_boundaries\",\n          \"basic/getting-started/concurrent\"\n        ]\n      },\n      {\n        \"type\": \"category\",\n        \"label\": \"Troubleshooting Handbook\",\n        \"items\": [\n          \"basic/troubleshooting/types\",\n          \"basic/troubleshooting/operators\",\n          \"basic/troubleshooting/utilities\",\n          \"basic/troubleshooting/non_ts_files\",\n          \"basic/troubleshooting/tsconfig\",\n          \"basic/troubleshooting/official_typings_bugs\",\n          \"basic/troubleshooting/learn_ts\"\n        ]\n      },\n      {\n        \"type\": \"category\",\n        \"label\": \"Recommendations\",\n        \"items\": [\n          \"basic/recommended/codebases\",\n          \"basic/recommended/talks\",\n          \"basic/recommended/resources\"\n        ]\n      },\n      \"basic/editor_integration\",\n      \"basic/linting\",\n      \"basic/examples\"\n    ],\n    \"HOC\": [\n      \"hoc/intro\",\n      \"hoc/full_example\",\n      \"hoc/react_hoc_docs\",\n      \"hoc/excluding_props\"\n    ],\n    \"Advanced\": [\n      \"advanced/intro\",\n      \"advanced/utility_types\",\n      \"advanced/patterns_by_usecase\",\n      \"advanced/patterns_by_version\",\n      \"advanced/misc_concerns\",\n      \"advanced/types_react_api\"\n    ],\n    \"Migration\": [\n      \"migration/intro\",\n      \"migration/js_docs\",\n      \"migration/from_js\",\n      \"migration/from_flow\"\n    ]\n  }\n}\n"
  },
  {
    "path": "website/src/css/custom.css",
    "content": ":root {\n  --ifm-color-primary: #138cd3;\n  --ifm-color-primary-dark: #117ebe;\n  --ifm-color-primary-darker: #1077b3;\n  --ifm-color-primary-darkest: #0c5a87;\n  --ifm-color-primary-light: #159ae8;\n  --ifm-color-primary-lighter: #1e9feb;\n  --ifm-color-primary-lightest: #3dacee;\n}\n\n.navbar__inner {\n  max-width: 1400px;\n  margin: 0 auto;\n}\n\n.navbar__title {\n  white-space: normal;\n  word-break: break-word;\n}\n\n.footer__logo {\n  max-width: 4rem;\n  max-height: 4rem;\n}\n\nmain details {\n  margin-top: 1rem;\n  margin-bottom: 1rem;\n  padding: 1rem 1rem 0;\n  border: 0.15rem solid var(--ifm-color-emphasis-300);\n  border-radius: var(--ifm-pagination-nav-border-radius);\n}\n\nmain details summary {\n  margin-bottom: 1rem;\n  outline: none;\n  /* Make it look like a link to notify user that it's clickable */\n  text-decoration: underline;\n\n  /* Refer to #309 */\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\nmain details summary:hover {\n  cursor: pointer;\n  /* Hide the underline on hover */\n  text-decoration: none;\n}\nmain details:hover {\n  border-color: var(--ifm-pagination-nav-color-hover);\n}\n\n.homePageBtns {\n  display: grid;\n  gap: 20px;\n}\n@media (min-width: 480px) {\n  .homePageBtns {\n    grid-template-columns: 1fr 1fr;\n  }\n}\n"
  },
  {
    "path": "website/src/pages/help.js",
    "content": "import React from \"react\";\nimport useDocusaurusContext from \"@docusaurus/useDocusaurusContext\";\nimport useBaseUrl from \"@docusaurus/useBaseUrl\";\nimport Link from \"@docusaurus/Link\";\nimport Layout from \"@theme/Layout\";\n\nconst SupportLink = ({ title, content }) => (\n  <div>\n    <h2>{title}</h2>\n    <div>{content}</div>\n  </div>\n);\n\nexport default function Help() {\n  const { siteConfig } = useDocusaurusContext();\n\n  const supportLinks = [\n    {\n      title: \"Browse Docs\",\n      content: (\n        <>\n          Learn more using the{\" \"}\n          <Link to={useBaseUrl(siteConfig.customFields.firstDoc)}>\n            documentation on this site\n          </Link>\n          .\n        </>\n      ),\n    },\n    {\n      title: \"Join the community\",\n      content: \"Ask questions about the documentation and project\",\n    },\n    {\n      title: \"Stay up to date\",\n      content: \"Find out what's new with this project\",\n    },\n  ];\n\n  return (\n    <Layout title=\"Help\" permalink=\"/help\" description=\"Help\">\n      <div className=\"container margin-vert--xl\">\n        <div>\n          <header>\n            <h1>Need help?</h1>\n          </header>\n          <p>This project is maintained by a dedicated group of people.</p>\n        </div>\n\n        <div className=\"row\">\n          {supportLinks.map((supportLink, i) => (\n            <div className=\"col col--4 margin-top--lg\" key={i}>\n              <SupportLink {...supportLink} />\n            </div>\n          ))}\n        </div>\n      </div>\n    </Layout>\n  );\n}\n"
  },
  {
    "path": "website/src/pages/index.js",
    "content": "import React from \"react\";\nimport Link from \"@docusaurus/Link\";\nimport useDocusaurusContext from \"@docusaurus/useDocusaurusContext\";\nimport useBaseUrl from \"@docusaurus/useBaseUrl\";\n\nimport Layout from \"@theme/Layout\";\n\nexport default function Home() {\n  const { siteConfig } = useDocusaurusContext();\n  return (\n    <Layout\n      title=\"React TypeScript Cheatsheets\"\n      permalink=\"/\"\n      description=\"React TypeScript Cheatsheets\"\n    >\n      <div className=\"hero text--center\">\n        <div className=\"container \">\n          <div className=\"padding-vert--md\">\n            <h1 className=\"hero__title\">{siteConfig.title}</h1>\n            <p className=\"hero__subtitle\">{siteConfig.tagline}</p>\n          </div>\n          <div className=\"homePageBtns\">\n            <Link\n              to={useBaseUrl(siteConfig.customFields.firstDoc)}\n              className=\"button button--lg button--outline button--primary\"\n            >\n              Getting started\n            </Link>\n            <Link\n              to={\"https://discord.gg/wTGS5z9\"}\n              className=\"button button--lg button--outline button--secondary\"\n            >\n              Join Official Discord\n            </Link>\n          </div>\n        </div>\n      </div>\n    </Layout>\n  );\n}\n"
  },
  {
    "path": "website/src/pages/users.js",
    "content": "import React from \"react\";\nimport useDocusaurusContext from \"@docusaurus/useDocusaurusContext\";\nimport Layout from \"@theme/Layout\";\n\n// TODO useless user showcase page ?\nexport default function Users() {\n  const { siteConfig } = useDocusaurusContext();\n  const { users, addUserUrl } = siteConfig.customFields;\n\n  return (\n    <Layout title=\"Users\" permalink=\"/users\" description=\"Users\">\n      <div className=\"container\">\n        <div className=\"margin-vert--xl text--center\">\n          <div>\n            <h1>Who is Using This?</h1>\n            <p>This project is used by many folks</p>\n          </div>\n          <div className=\"row\">\n            {users && users.length>0&& users.map((user) => (\n              <a\n                className=\"col-2\"\n                href={user.infoLink}\n                key={user.infoLink}\n                style={{ flexGrow: 1 }}\n              >\n                <img\n                  className=\"padding--md\"\n                  src={user.image}\n                  alt={user.caption}\n                  title={user.caption}\n                  style={{\n                    maxHeight: 128,\n                    width: 128,\n                  }}\n                />\n              </a>\n            ))}\n          </div>\n          <p>Are you using this project?</p>\n          <a\n            href={addUserUrl}\n            className=\"button button--lg button--outline button--primary\"\n          >\n            Add your company\n          </a>\n        </div>\n      </div>\n    </Layout>\n  );\n}\n"
  }
]