Showing preview only (432K chars total). Download the full file or copy to clipboard to get everything.
Repository: typescript-cheatsheets/react
Branch: main
Commit: c299ceb2d0d2
Files: 73
Total size: 410.1 KB
Directory structure:
gitextract_e6_naeoq/
├── .all-contributorsrc
├── .dockerignore
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── advanced-cheatsheet.md
│ │ ├── basic-cheatsheet.md
│ │ ├── general-react-ts-question.md
│ │ ├── hoc-cheatsheet.md
│ │ └── migrating-cheatsheet.md
│ ├── pull_request_template.md
│ ├── stale.yml
│ └── workflows/
│ ├── main.yml
│ └── mlc_config.json
├── .gitignore
├── .husky/
│ └── pre-commit
├── .nvmrc
├── CONTRIBUTING.md
├── CONTRIBUTORS.md
├── LICENSE
├── README.md
├── code-of-conduct.md
├── copyFile.js
├── docs/
│ ├── advanced/
│ │ ├── index.md
│ │ ├── misc-concerns.md
│ │ ├── patterns_by_usecase.md
│ │ ├── patterns_by_version.md
│ │ ├── types-react-ap.md
│ │ └── utility-types.md
│ ├── basic/
│ │ ├── editor-integration.md
│ │ ├── examples.md
│ │ ├── getting-started/
│ │ │ ├── basic-type-examples.md
│ │ │ ├── class-components.md
│ │ │ ├── concurrent.md
│ │ │ ├── context.md
│ │ │ ├── default-props.md
│ │ │ ├── error-boundaries.md
│ │ │ ├── forms-and-events.md
│ │ │ ├── forward-create-ref.md
│ │ │ ├── function-components.md
│ │ │ ├── hooks.md
│ │ │ └── portals.md
│ │ ├── linting.md
│ │ ├── recommended/
│ │ │ ├── codebases.md
│ │ │ ├── resources.md
│ │ │ └── talks.md
│ │ ├── setup.md
│ │ └── troubleshooting/
│ │ ├── learn-ts.md
│ │ ├── non-ts-files.md
│ │ ├── official-typings-bugs.md
│ │ ├── operators.md
│ │ ├── ts-config.md
│ │ ├── types.md
│ │ └── utilities.md
│ ├── hoc/
│ │ ├── excluding-props.md
│ │ ├── full-example.md
│ │ ├── index.md
│ │ └── react-hoc-docs.md
│ ├── migration/
│ │ ├── from-flow.md
│ │ ├── from-js.md
│ │ ├── index.md
│ │ └── js-docs.md
│ └── react-types/
│ ├── ComponentProps.md
│ ├── ReactNode.md
│ └── index.md
├── genReadme.js
├── netlify.toml
├── package.json
└── website/
├── README.md
├── docusaurus.config.js
├── package.json
├── sidebars.json
└── src/
├── css/
│ └── custom.css
└── pages/
├── help.js
├── index.js
└── users.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .all-contributorsrc
================================================
{
"files": [
"CONTRIBUTORS.md",
"README.md"
],
"imageSize": 100,
"commit": true,
"commitConvention": "angular",
"contributors": [
{
"login": "ferdaber",
"name": "Ferdy Budhidharma",
"avatar_url": "https://avatars2.githubusercontent.com/u/12239873?v=4",
"profile": "https://github.com/ferdaber",
"contributions": [
"review",
"maintenance",
"content"
]
},
{
"login": "sw-yx",
"name": "swyx",
"avatar_url": "https://avatars1.githubusercontent.com/u/6764957?v=4",
"profile": "https://twitter.com/swyx",
"contributions": [
"ideas",
"review",
"maintenance",
"content",
"question"
]
},
{
"login": "eps1lon",
"name": "Sebastian Silbermann",
"avatar_url": "https://avatars3.githubusercontent.com/u/12292047?v=4",
"profile": "https://github.com/eps1lon",
"contributions": [
"review",
"maintenance",
"content"
]
},
{
"login": "Attrash-Islam",
"name": "Islam Attrash",
"avatar_url": "https://avatars0.githubusercontent.com/u/7091543?v=4",
"profile": "https://www.linkedin.com/in/islam-attrash-46703a94/",
"contributions": [
"maintenance",
"content"
]
},
{
"login": "stephenkoo",
"name": "Stephen Koo",
"avatar_url": "https://avatars2.githubusercontent.com/u/18624246?v=4",
"profile": "https://stephenkoo.github.io/",
"contributions": [
"question",
"example"
]
},
{
"login": "andreasgruenh",
"name": "Andreas",
"avatar_url": "https://avatars2.githubusercontent.com/u/12122390?v=4",
"profile": "https://github.com/andreasgruenh",
"contributions": [
"code",
"doc",
"infra"
]
},
{
"login": "arvindcheenu",
"name": "Arvind Srinivasan",
"avatar_url": "https://avatars2.githubusercontent.com/u/13925213?v=4",
"profile": "https://github.com/arvindcheenu",
"contributions": [
"code",
"content",
"doc",
"maintenance"
]
},
{
"login": "williamrjribeiro",
"name": "William R. J. Ribeiro",
"avatar_url": "https://avatars2.githubusercontent.com/u/1503499?v=4",
"profile": "http://www.williamrjribeiro.com",
"contributions": [
"ideas"
]
},
{
"login": "alexandrudanpop",
"name": "Alexandru-Dan Pop",
"avatar_url": "https://avatars0.githubusercontent.com/u/15979292?v=4",
"profile": "https://alexandrudanpop.dev/",
"contributions": [
"doc"
]
},
{
"login": "mastorm",
"name": "Mathias Storm",
"avatar_url": "https://avatars1.githubusercontent.com/u/10759336?v=4",
"profile": "https://github.com/mastorm",
"contributions": [
"doc"
]
},
{
"login": "dance2die",
"name": "Sung M. Kim",
"avatar_url": "https://avatars1.githubusercontent.com/u/8465237?v=4",
"profile": "https://twitter.com/dance2die",
"contributions": [
"doc",
"ideas"
]
},
{
"login": "ryota-murakami",
"name": "Ryota Murakami",
"avatar_url": "https://avatars2.githubusercontent.com/u/5501268?v=4",
"profile": "https://ryota-murakami.github.io/",
"contributions": [
"example",
"doc"
]
},
{
"login": "arpi17",
"name": "Árpád Illyés",
"avatar_url": "https://avatars1.githubusercontent.com/u/13800404?v=4",
"profile": "https://github.com/arpi17",
"contributions": [
"code"
]
},
{
"login": "xamgore",
"name": "Igor Strebezhev",
"avatar_url": "https://avatars3.githubusercontent.com/u/4586392?v=4",
"profile": "https://twitter.com/xamgore",
"contributions": [
"ideas",
"doc"
]
},
{
"login": "dwjohnston",
"name": "David Johnston",
"avatar_url": "https://avatars2.githubusercontent.com/u/2467377?v=4",
"profile": "https://geoplanets.io",
"contributions": [
"doc"
]
},
{
"login": "kripod",
"name": "Kristóf Poduszló",
"avatar_url": "https://avatars3.githubusercontent.com/u/14854048?v=4",
"profile": "https://github.com/kripod",
"contributions": [
"doc"
]
},
{
"login": "glaschu1",
"name": "james glasgow",
"avatar_url": "https://avatars3.githubusercontent.com/u/10838852?v=4",
"profile": "http://www.novusstudio.com/",
"contributions": [
"doc"
]
},
{
"login": "Winner95",
"name": "Ivan",
"avatar_url": "https://avatars0.githubusercontent.com/u/13730032?v=4",
"profile": "https://www.linkedin.com/in/iigrekov/",
"contributions": [
"code"
]
},
{
"login": "selrond",
"name": "Sebastian Andil",
"avatar_url": "https://avatars1.githubusercontent.com/u/6603389?v=4",
"profile": "http://sebastianandil.com",
"contributions": [
"doc"
]
},
{
"login": "adnanhusain15",
"name": "Adnan Husain",
"avatar_url": "https://avatars2.githubusercontent.com/u/36721076?v=4",
"profile": "https://github.com/adnanhusain15",
"contributions": [
"doc"
]
},
{
"login": "artola",
"name": "martin",
"avatar_url": "https://avatars0.githubusercontent.com/u/11500763?v=4",
"profile": "https://github.com/artola",
"contributions": [
"doc"
]
},
{
"login": "filiptammergard",
"name": "Filip Tammergård",
"avatar_url": "https://avatars.githubusercontent.com/u/44197016?v=4",
"profile": "https://tammergard.se",
"contributions": [
"doc",
"code"
]
},
{
"login": "jsjoeio",
"name": "Joe Previte",
"avatar_url": "https://avatars.githubusercontent.com/u/3806031?v=4",
"profile": "https://englishbyte.com",
"contributions": [
"doc"
]
},
{
"login": "sasirura",
"name": "Sasiru Ravihansa",
"avatar_url": "https://avatars.githubusercontent.com/u/42542164?v=4",
"profile": "https://github.com/sasirura",
"contributions": [
"doc"
]
}
],
"contributorsPerLine": 7,
"projectName": "react",
"projectOwner": "typescript-cheatsheets",
"repoType": "github",
"repoHost": "https://github.com",
"skipCi": true,
"commitType": "docs"
}
================================================
FILE: .dockerignore
================================================
*/node_modules
*.log
================================================
FILE: .github/ISSUE_TEMPLATE/advanced-cheatsheet.md
================================================
---
name: Advanced Cheatsheet
about: Report Issue/Suggest an idea for Advanced Cheatsheet
title: "[Advanced] ISSUE_TITLE_HERE"
labels: ADVANCED
assignees: ""
---
**What cheatsheet is this about? (if applicable)**
Advanced cheatsheet
**What's your issue or idea?**
_Write here_
================================================
FILE: .github/ISSUE_TEMPLATE/basic-cheatsheet.md
================================================
---
name: Basic Cheatsheet
about: Report Issue/Suggest an idea for Basic Cheatsheet
title: "[Basic] ISSUE_TITLE_HERE"
labels: BASIC
assignees: sw-yx
---
**What cheatsheet is this about? (if applicable)**
Basic cheatsheet
**What's your issue or idea?**
_Write here_
**(If applicable) Reproduction of issue in TypeScript Playground**
_[start with the basic TS + React template](https://www.typescriptlang.org/play/?jsx=2&esModuleInterop=true&q=222#example/typescript-with-react)_
================================================
FILE: .github/ISSUE_TEMPLATE/general-react-ts-question.md
================================================
---
name: General React+TS Question
about: Questions are welcome! We want to know and solve your pain points.
title: "[Question] QUESTION_TITLE_HERE"
labels: good first issue
assignees: sw-yx
---
**(If applicable) Reproduction of issue in TypeScript Playground**
_[start with the basic TS + React template](https://www.typescriptlang.org/play/?jsx=2&esModuleInterop=true&q=222#example/typescript-with-react)_
================================================
FILE: .github/ISSUE_TEMPLATE/hoc-cheatsheet.md
================================================
---
name: HOC Cheatsheet
about: Report Issue/Suggest an idea for HOC Cheatsheet
title: "[HOC] ISSUE_TITLE_HERE"
labels: HOC
assignees: ""
---
**What cheatsheet is this about? (if applicable)**
HOC cheatsheet
**What's your issue or idea?**
_Write here_
================================================
FILE: .github/ISSUE_TEMPLATE/migrating-cheatsheet.md
================================================
---
name: Migrating Cheatsheet
about: Report Issue/Suggest an idea for Migrating Cheatsheet
title: "[Migrating] ISSUE_TITLE_HERE"
labels: MIGRATING
assignees: ""
---
**What cheatsheet is this about? (if applicable)**
Migrating cheatsheet
**What's your issue or idea?**
_Write here_
================================================
FILE: .github/pull_request_template.md
================================================
Thanks for contributing!
- **If you are making a significant PR**, please make sure there is an open issue first
- **If you're just fixing typos or adding small notes**, a brief explanation of why you'd like to add it would be nice :)
**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._
================================================
FILE: .github/stale.yml
================================================
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: wontfix
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions!
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false
================================================
FILE: .github/workflows/main.yml
================================================
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
files-up-to-date:
runs-on: ubuntu-latest
steps:
- name: Checkout commit
uses: actions/checkout@v4
- name: Setup node
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: yarn
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: "`yarn format` changes committed?"
run: yarn format:check
- name: "`yarn gen-readme` changes committed?"
run: |
yarn gen-readme
git diff --exit-code
================================================
FILE: .github/workflows/mlc_config.json
================================================
{
"aliveStatusCodes": [200, 429]
}
================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# Idea / Jetbrains IDE
.idea
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.pnp.*
# Miscellaneous
.history
.DS_Store
# Docusaurus files
website/build
website/.docusaurus
website/.cache-loader
# copy of contributors for the website
website/src/pages/contributing.md
website/src/pages/contributors.md
# Local Netlify folder
.netlify
# Lock-files
package-lock.json
yarn.lock
================================================
FILE: .husky/pre-commit
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn pretty-quick --staged
================================================
FILE: .nvmrc
================================================
20.x
================================================
FILE: CONTRIBUTING.md
================================================
# Let's Contribute Together! 🚀
We 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:
## 📋 Core Principles
1. **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.
2. **Collapsible Explanations**: Keep explanations short and sweet, limited to 1-2 sentences. For more in-depth explanations, use `details` tags to provide additional context.
3. **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.
4. **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.
Your contributions will help countless developers, including your future self! 🙌
## 📁 Project Structure
- **Content in `/docs`**: All the content resides here.
- The content in `/docs/basic` is compiled into `README.md` to ensure that it's easy to read on GitHub.
- **`/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!
The website is deployed on Netlify, under swyx's personal account.
To run the docsite locally, follow these steps:
```bash
yarn # Install dependencies
## Ensure dependencies are also installed in /website
cd website && yarn start
```
Here's an example of the expected output when the development server starts successfully:
```
yarn run v1.22.4
warning package.json: No license field
$ docusaurus start
Starting the development server...
✔ Client
Compiled successfully in 9.61s
ℹ 「wds」: Project is running at http://localhost:3000/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /Users/wanshawn/Work/react-typescript-cheatsheet/website
ℹ 「wds」: 404s will fallback to /index.html
✔ Client
Compiled successfully in 116.41ms
```
Let's work together to enhance this resource and make it even more valuable to the developer community! 🌟👩💻👨💻
================================================
FILE: CONTRIBUTORS.md
================================================
## Contributors
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
</tr>
<tr>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
</tr>
<tr>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
</tr>
<tr>
<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>
<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>
<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>
</tr>
</tbody>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018 shawn wang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# React TypeScript Cheatsheet
Cheatsheet for using React with TypeScript.
---
<a href="https://github.com/typescript-cheatsheets/react/issues/81">
<img
height="90"
width="90"
alt="react + ts logo"
src="https://user-images.githubusercontent.com/84442212/194379444-02e5ec69-5e6c-4100-bd7a-c31d628af29c.png"
align="left"
/>
</a>
[**Web docs**](https://react-typescript-cheatsheet.netlify.app/docs/basic/setup) |
[Contribute!](https://github.com/typescript-cheatsheets/react/blob/main/CONTRIBUTING.md) |
[Ask!](https://github.com/typescript-cheatsheets/react/issues/new/choose)
: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:
---
[](/CONTRIBUTORS.md) | [](https://discord.gg/wTGS5z9)
- [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**
- Focus on opinionated best practices, copy+pastable examples.
- Explains some basic TS types usage and setup along the way.
- Answers the most Frequently Asked Questions.
- Does not cover generic type logic in detail. Instead we prefer to teach simple troubleshooting techniques for newbies.
- The goal is to get effective with TS without learning _too much_ TS.
- [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**.
- It also has miscellaneous tips and tricks for pro users.
- Advice for contributing to DefinitelyTyped.
- The goal is to take _full advantage_ of TypeScript.
- [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**.
- We do not try to convince people to switch, only to help people who have already decided.
- ⚠️This is a new cheatsheet, all assistance is welcome.
- [The HOC Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/hoc) specifically teaches people to write HOCs with examples.
- Familiarity with [Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html) is necessary.
- ⚠️This is the newest cheatsheet, all assistance is welcome.
---
## Basic Cheatsheet
### Basic Cheatsheet Table of Contents
<details>
<summary><b>Expand Table of Contents</b></summary>
- [React TypeScript Cheatsheet](#react-typescript-cheatsheet)
- [Basic Cheatsheet](#basic-cheatsheet)
- [Basic Cheatsheet Table of Contents](#basic-cheatsheet-table-of-contents)
- [Section 1: Setup](#section-1-setup)
- [Prerequisites](#prerequisites)
- [React and TypeScript starter kits](#react-and-typescript-starter-kits)
- [Try React and TypeScript online](#try-react-and-typescript-online)
- [Section 2: Getting Started](#section-2-getting-started)
- [Function Components](#function-components)
- [Hooks](#hooks)
- [useState](#usestate)
- [useCallback](#usecallback)
- [useReducer](#usereducer)
- [useEffect / useLayoutEffect](#useeffect--uselayouteffect)
- [useRef](#useref)
- [Option 1: DOM element ref](#option-1-dom-element-ref)
- [Option 2: Mutable value ref](#option-2-mutable-value-ref)
- [See also](#see-also)
- [useImperativeHandle](#useimperativehandle)
- [See also:](#see-also-1)
- [Custom Hooks](#custom-hooks)
- [More Hooks + TypeScript reading:](#more-hooks--typescript-reading)
- [Example React Hooks + TypeScript Libraries:](#example-react-hooks--typescript-libraries)
- [Class Components](#class-components)
- [Typing getDerivedStateFromProps](#typing-getderivedstatefromprops)
- [You May Not Need `defaultProps`](#you-may-not-need-defaultprops)
- [Typing `defaultProps`](#typing-defaultprops)
- [Consuming Props of a Component with defaultProps](#consuming-props-of-a-component-with-defaultprops)
- [Problem Statement](#problem-statement)
- [Solution](#solution)
- [Misc Discussions and Knowledge](#misc-discussions-and-knowledge)
- [Typing Component Props](#typing-component-props)
- [Basic Prop Types Examples](#basic-prop-types-examples)
- [`object` as the non-primitive type](#object-as-the-non-primitive-type)
- [Empty interface, `{}` and `Object`](#empty-interface--and-object)
- [Useful React Prop Type Examples](#useful-react-prop-type-examples)
- [Types or Interfaces?](#types-or-interfaces)
- [TL;DR](#tldr)
- [More Advice](#more-advice)
- [Useful table for Types vs Interfaces](#useful-table-for-types-vs-interfaces)
- [getDerivedStateFromProps](#getderivedstatefromprops)
- [Forms and Events](#forms-and-events)
- [List of event types](#list-of-event-types)
- [Context](#context)
- [Basic example](#basic-example)
- [Without default context value](#without-default-context-value)
- [Type assertion as an alternative](#type-assertion-as-an-alternative)
- [forwardRef/createRef](#forwardrefcreateref)
- [Generic forwardRefs](#generic-forwardrefs)
- [Option 1 - Wrapper component](#option-1---wrapper-component)
- [Option 2 - Redeclare forwardRef](#option-2---redeclare-forwardref)
- [Option 3 - Call signature](#option-3---call-signature)
- [More Info](#more-info)
- [Portals](#portals)
- [Error Boundaries](#error-boundaries)
- [Option 1: Using react-error-boundary](#option-1-using-react-error-boundary)
- [Option 2: Writing your custom error boundary component](#option-2-writing-your-custom-error-boundary-component)
- [Concurrent React/React Suspense](#concurrent-reactreact-suspense)
- [Troubleshooting Handbook: Types](#troubleshooting-handbook-types)
- [Union Types and Type Guarding](#union-types-and-type-guarding)
- [Optional Types](#optional-types)
- [Enum Types](#enum-types)
- [Type Assertion](#type-assertion)
- [Simulating Nominal Types](#simulating-nominal-types)
- [Intersection Types](#intersection-types)
- [Union Types](#union-types)
- [Overloading Function Types](#overloading-function-types)
- [Using Inferred Types](#using-inferred-types)
- [Using Partial Types](#using-partial-types)
- [The Types I need weren't exported!](#the-types-i-need-werent-exported)
- [The Types I need don't exist!](#the-types-i-need-dont-exist)
- [Slapping `any` on everything](#slapping-any-on-everything)
- [Autogenerate types](#autogenerate-types)
- [Typing Exported Hooks](#typing-exported-hooks)
- [Typing Exported Components](#typing-exported-components)
- [Frequent Known Problems with TypeScript](#frequent-known-problems-with-typescript)
- [TypeScript doesn't narrow after an object element null check](#typescript-doesnt-narrow-after-an-object-element-null-check)
- [TypeScript doesn't let you restrict the type of children](#typescript-doesnt-let-you-restrict-the-type-of-children)
- [Troubleshooting Handbook: Operators](#troubleshooting-handbook-operators)
- [Troubleshooting Handbook: Utilities](#troubleshooting-handbook-utilities)
- [Troubleshooting Handbook: tsconfig.json](#troubleshooting-handbook-tsconfigjson)
- [Troubleshooting Handbook: Fixing bugs in official typings](#troubleshooting-handbook-fixing-bugs-in-official-typings)
- [Troubleshooting Handbook: Globals, Images and other non-TS files](#troubleshooting-handbook-globals-images-and-other-non-ts-files)
- [Editor Tooling and Integration](#editor-tooling-and-integration)
- [Linting](#linting)
- [Other React + TypeScript resources](#other-react--typescript-resources)
- [Recommended React + TypeScript talks](#recommended-react--typescript-talks)
- [Time to Really Learn TypeScript](#time-to-really-learn-typescript)
- [Example App](#example-app)
- [My question isn't answered here!](#my-question-isnt-answered-here)
- [Contributors](#contributors)
</details>
<!--START-SECTION:setup-->
### Section 1: Setup
#### Prerequisites
You 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:
- Basic understanding of [React](https://react.dev/).
- 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).
In the cheatsheet we assume you are using the latest versions of React and TypeScript.
#### React and TypeScript starter kits
React 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:
- [Next.js](https://nextjs.org/docs/basic-features/typescript): `npx create-next-app@latest --ts`
- [Remix](https://remix.run/docs/tutorials/blog): `npx create-remix@latest`
- [Gatsby](https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/): `npm init gatsby --ts`
- [Expo](https://docs.expo.dev/guides/typescript/): `npx create-expo-app -t with-typescript`
#### Try React and TypeScript online
There are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.
- [TypeScript playground](https://www.typescriptlang.org/play?target=8&jsx=4#code/JYWwDg9gTgLgBAbzgVwM4FMDKMCGN0A0KGAogGZnoDG8AvnGVBCHAORTo42sDcAsAChB6AB6RYcKhAB2qeAGEIyafihwAvHAAUASg0A+RILiSZcuAG0pymEQwxFNgLobiWXPi0AGHfyECTNHRyShotXQMjAJM4ABMIKmQQdBUAOhhgGAAbdFcAAwBNJUks4CoAa3RYuAASBGsVegzk1Dy-E1pfQWM4DhhkKGltHpMAHn0RmNGwfSLkErLK6vqlRrhm9FRRgHoZybGAI2QYGBk4GXlSivUECPVDe0cVLQb4AGo4AEYdWgnomJil0WcGS+zgOyOJxkfwBOxhcC6AlogiAA)
- [StackBlitz](https://stackblitz.com/fork/react-ts)
- [CodeSandbox](https://ts.react.new/)
<!--END-SECTION:setup-->
### Section 2: Getting Started
<!--START-SECTION:function-components-->
#### Function Components
These can be written as normal functions that take a `props` argument and return a JSX element.
```tsx
// Declaring type of props - see "Typing Component Props" for more examples
type AppProps = {
message: string;
}; /* use `interface` if exporting so that consumers can extend */
// Easiest way to declare a Function Component; return type is inferred.
const App = ({ message }: AppProps) => <div>{message}</div>;
// You can choose to annotate the return type so an error is raised if you accidentally return some other type
const App = ({ message }: AppProps): React.JSX.Element => <div>{message}</div>;
// You can also inline the type declaration; eliminates naming the prop types, but looks repetitive
const App = ({ message }: { message: string }) => <div>{message}</div>;
// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.
// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
// or
const App: React.FC<AppProps> = ({ message }) => <div>{message}</div>;
```
> 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)).
<details>
<summary><b>Why is <code>React.FC</code> not needed? What about <code>React.FunctionComponent</code>/<code>React.VoidFunctionComponent</code>?</b></summary>
You may see this in many React+TypeScript codebases:
```tsx
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
```
However, 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).
Some differences from the "normal function" version:
- `React.FunctionComponent` is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).
- It provides typechecking and autocomplete for static properties like `displayName`, `propTypes`, and `defaultProps`.
- 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.
- 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).
```tsx
// before React 18 types
const Title: React.FunctionComponent<{ title: string }> = ({
children,
title,
}) => <div title={title}>{children}</div>;
```
<details>
<summary>(Deprecated)<b>Using <code>React.VoidFunctionComponent</code> or <code>React.VFC</code> instead</b></summary>
In [@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.
However, 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+.
Please use regular function components or `React.FC` instead.
```ts
type Props = { foo: string };
// OK now, in future, error
const FunctionComponent: React.FunctionComponent<Props> = ({
foo,
children,
}: Props) => {
return (
<div>
{foo} {children}
</div>
); // OK
};
// Error now, in future, deprecated
const VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({
foo,
children,
}) => {
return (
<div>
{foo}
{children}
</div>
);
};
```
</details>
- _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.
In most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of `React.FunctionComponent`.
</details>
<!--END-SECTION:function-components-->
<!--START-SECTION:hooks-->
#### Hooks
Hooks are [supported in `@types/react` from v16.8 up](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031).
#### useState
Type inference works very well for simple values:
```tsx
const [state, setState] = useState(false);
// `state` is inferred to be a boolean
// `setState` only takes booleans
```
See 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.
However, 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:
```tsx
const [user, setUser] = useState<User | null>(null);
// later...
setUser(newUser);
```
You can also use type assertions if a state is initialized soon after setup and always has a value after:
```tsx
const [user, setUser] = useState<User>({} as User);
// later...
setUser(newUser);
```
This 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.
#### useCallback
You can type the `useCallback` just like any other function.
```ts
const memoizedCallback = useCallback(
(param1: string, param2: number) => {
console.log(param1, param2)
return { ok: true }
},
[...],
);
/**
* VSCode will show the following type:
* const memoizedCallback:
* (param1: string, param2: number) => { ok: boolean }
*/
```
Note that for React < 18, the function signature of `useCallback` typed arguments as `any[]` by default:
```ts
function useCallback<T extends (...args: any[]) => any>(
callback: T,
deps: DependencyList
): T;
```
In React >= 18, the function signature of `useCallback` changed to the following:
```ts
function useCallback<T extends Function>(callback: T, deps: DependencyList): T;
```
Therefore, the following code will yield "`Parameter 'e' implicitly has an 'any' type.`" error in React >= 18, but not <17.
```ts
// @ts-expect-error Parameter 'e' implicitly has 'any' type.
useCallback((e) => {}, []);
// Explicit 'any' type.
useCallback((e: any) => {}, []);
```
#### useReducer
You 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.
```tsx
import { useReducer } from "react";
const initialState = { count: 0 };
type ACTIONTYPE =
| { type: "increment"; payload: number }
| { type: "decrement"; payload: string };
function reducer(state: typeof initialState, action: ACTIONTYPE) {
switch (action.type) {
case "increment":
return { count: state.count + action.payload };
case "decrement":
return { count: state.count - Number(action.payload) };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: "decrement", payload: "5" })}>
-
</button>
<button onClick={() => dispatch({ type: "increment", payload: 5 })}>
+
</button>
</>
);
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6WfTDRSvKnMgpEIgBhxTIJwEQANZSWRjI5SdPIF1u8RXMayZ7lSphEnRWLxbFNagAVmomhF6fZqYA9OXKxxM2KQWWK1WoTW643m63pB2u+7e-3SkEQsPamOGik1FO55p08jl6vdxuKcvv8h4yAmhAA)
<details>
<summary><b>Usage with <code>Reducer</code> from <code>redux</code></b></summary>
In 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.
So the above reducer example becomes:
```tsx
import { Reducer } from 'redux';
export function reducer: Reducer<AppState, Action>() {}
```
</details>
#### useEffect / useLayoutEffect
Both 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:
```ts
function DelayedEffect(props: { timerMs: number }) {
const { timerMs } = props;
useEffect(
() =>
setTimeout(() => {
/* do stuff */
}, timerMs),
[timerMs]
);
// bad example! setTimeout implicitly returns a number
// because the arrow function body isn't wrapped in curly braces
return null;
}
```
<details>
<summary><b>Solution to the above example</b></summary>
```tsx
function DelayedEffect(props: { timerMs: number }) {
const { timerMs } = props;
useEffect(() => {
setTimeout(() => {
/* do stuff */
}, timerMs);
}, [timerMs]);
// better; use the void keyword to make sure you return undefined
return null;
}
```
</details>
#### useRef
In 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.
##### Option 1: DOM element ref
**[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:
```tsx
function Foo() {
// - If possible, prefer as specific as possible. For example, HTMLDivElement
// is better than HTMLElement and way better than Element.
// - Technical-wise, this returns RefObject<HTMLDivElement>
const divRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// Note that ref.current may be null. This is expected, because you may
// conditionally render the ref-ed element, or you may forget to assign it
if (!divRef.current) throw Error("divRef is not assigned");
// Now divRef.current is sure to be HTMLDivElement
doSomethingWith(divRef.current);
});
// Give the ref to an element so React can manage it for you
return <div ref={divRef}>etc</div>;
}
```
If you are sure that `divRef.current` will never be null, it is also possible to use the non-null assertion operator `!`:
```tsx
const divRef = useRef<HTMLDivElement>(null!);
// Later... No need to check if it is null
doSomethingWith(divRef.current);
```
Note 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.
<details>
<summary><b>Tip: Choosing which <code>HTMLElement</code> to use</b></summary>
Refs 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:

</details>
##### Option 2: Mutable value ref
**[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:
```tsx
function Foo() {
// Technical-wise, this returns MutableRefObject<number | null>
const intervalRef = useRef<number | null>(null);
// You manage the ref yourself (that's why it's called MutableRefObject!)
useEffect(() => {
intervalRef.current = setInterval(...);
return () => clearInterval(intervalRef.current);
}, []);
// The ref is not passed to any element's "ref" prop
return <button onClick={/* clearInterval the ref */}>Cancel timer</button>;
}
```
##### See also
- [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)
- [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)
#### useImperativeHandle
Based on this [Stackoverflow answer](https://stackoverflow.com/a/69292925/5415299):
```tsx
// Countdown.tsx
// Define the handle types which will be passed to the forwardRef
export type CountdownHandle = {
start: () => void;
};
type CountdownProps = {};
const Countdown = forwardRef<CountdownHandle, CountdownProps>((props, ref) => {
useImperativeHandle(ref, () => ({
// start() has type inference here
start() {
alert("Start");
},
}));
return <div>Countdown</div>;
});
```
```tsx
// The component uses the Countdown component
import Countdown, { CountdownHandle } from "./Countdown.tsx";
function App() {
const countdownEl = useRef<CountdownHandle>(null);
useEffect(() => {
if (countdownEl.current) {
// start() has type inference here as well
countdownEl.current.start();
}
}, []);
return <Countdown ref={countdownEl} />;
}
```
##### See also:
- [Using ForwardRefRenderFunction](https://stackoverflow.com/a/62258685/5415299)
#### Custom Hooks
If 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):
```tsx
import { useState } from "react";
export function useLoading() {
const [isLoading, setState] = useState(false);
const load = (aPromise: Promise<any>) => {
setState(true);
return aPromise.finally(() => setState(false));
};
return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?target=5&jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCpAD0ljkwFcA7DYCZuRgZyQBkIKACbBmAcwAUASjgBvCnDhoO3eAG1g3AcNFiANHF4wAyjBQwkAXTgBeRMRgA6HklPmkEzCgA2vKQG4FJRV4b0EhWzgJFAAFHBBNJAAuODjcRIAeFGYATwA+GRs8uSDFIzcLCRgoRiQA0rgiGEYoTlj4xMdMUR9vHIlpW2Lys0qvXzr68kUAX0DpxqRm1rgNLXDdAzDhaxRuYOZVfzgAehO4UUwkKH21ACMICG9UZgMYHLAkCEw4baFrUSqVARb5RB5PF5wAA+cHen1BfykaksFBmQA)
This way, when you destructure you actually get the right types based on destructure position.
<details>
<summary><b>Alternative: Asserting a tuple return type</b></summary>
If you are [having trouble with const assertions](https://github.com/babel/babel/issues/9800), you can also assert or define the function return types:
```tsx
import { useState } from "react";
export function useLoading() {
const [isLoading, setState] = useState(false);
const load = (aPromise: Promise<any>) => {
setState(true);
return aPromise.finally(() => setState(false));
};
return [isLoading, load] as [
boolean,
(aPromise: Promise<any>) => Promise<any>
];
}
```
A helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:
```tsx
function tuplify<T extends any[]>(...elements: T) {
return elements;
}
function useArray() {
const numberValue = useRef(3).current;
const functionValue = useRef(() => {}).current;
return [numberValue, functionValue]; // type is (number | (() => void))[]
}
function useTuple() {
const numberValue = useRef(3).current;
const functionValue = useRef(() => {}).current;
return tuplify(numberValue, functionValue); // type is [number, () => void]
}
```
</details>
Note that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however.
#### More Hooks + TypeScript reading:
- https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d
- https://fettblog.eu/typescript-react/hooks/#useref
If you are writing a React Hooks library, don't forget that you should also expose your types for users to use.
#### Example React Hooks + TypeScript Libraries:
- https://github.com/mweststrate/use-st8
- https://github.com/palmerhq/the-platform
- https://github.com/sw-yx/hooks
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
<!--END-SECTION:hooks-->
<!--START-SECTION:class-components-->
#### Class Components
Within 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:
```tsx
type MyProps = {
// using `interface` is also ok
message: string;
};
type MyState = {
count: number; // like this
};
class App extends React.Component<MyProps, MyState> {
state: MyState = {
// optional second annotation for better type inference
count: 0,
};
render() {
return (
<div>
{this.props.message} {this.state.count}
</div>
);
}
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgFlqAFHMAZzgF44BvCuHAD0QuAFd2wAHYBzOAANpMJFEzok8uME4oANuwhwIAawFwQSduxQykALjjsYUaTIDcFAL4fyNOo2oAZRgUZW4+MzQIMSkYBykxEAAjFTdhUV1gY3oYAAttLx80XRQrOABBMDA4JAAPZSkAE05kdBgAOgBhXEgpJFiAHiZWCA4AGgDg0KQAPgjyQSdphyYpsJ5+BcF0ozAYYAgpPUckKKa4FCkpCBD9w7hMaDgUmGUoOD96aUwVfrQkMyCKIxOJwAAMZm8ZiITRUAAoAJTzbZwIgwMRQKRwOGA7YDRrAABuM1xKN4eW07TAbHY7QsVhsSE8fAptKWynawNinlJcAGQgJxNxCJ8gh55E8QA)
Don't forget that you can export/import/extend these types/interfaces for reuse.
<details>
<summary><b>Why annotate <code>state</code> twice?</b></summary>
It 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.
This 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.
[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57).
</details>
<details>
<summary><b>No need for <code>readonly</code></b></summary>
You often see sample code include `readonly` to mark props and state immutable:
```tsx
type MyProps = {
readonly message: string;
};
type MyState = {
readonly count: number;
};
```
This is not necessary as `React.Component<P,S>` already marks them as immutable. ([See PR and discussion!](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813))
</details>
**Class Methods**: Do it like normal, but just remember any arguments for your functions also need to be typed:
```tsx
class App extends React.Component<{ message: string }, { count: number }> {
state = { count: 0 };
render() {
return (
<div onClick={() => this.increment(1)}>
{this.props.message} {this.state.count}
</div>
);
}
increment = (amt: number) => {
// like this
this.setState((state) => ({
count: state.count + amt,
}));
};
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN5wQSBigDmSAFxw6MKMB5q4AXwA0cRWggBXHjG09rIAEZIoJgHwWKcHTBTccAC8FnBWtvZwAAwmANw+cET8bgAUAJTe5L6+RDDWUDxwKQnZcLJ8wABucBA8YtTAaADWQfLpwV4wABbAdCIGaETKdikAjGnGHiWlFt29ImA4YH3KqhrGsz19ugFIIuF2xtO+sgD0FZVTWdlp8ddH1wNDMsFFKCCRji5uGUFe8tNTqc4A0mkg4HM6NNISI6EgYABlfzcFI7QJ-IoA66lA6RNF7XFwADUcHeMGmxjStwSxjuxiAA)
**Class Properties**: If you need to declare class properties for later use, just declare it like `state`, but without assignment:
```tsx
class App extends React.Component<{
message: string;
}> {
pointer: number; // like this
componentDidMount() {
this.pointer = 3;
}
render() {
return (
<div>
{this.props.message} and {this.pointer}
</div>
);
}
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN4U4cEEgYoA5kgBccOjCjAeGgNwUAvgD44i8sshHuUXTwCuIAEZIoJuAHo-OGpgAGskOBgAC2A6JTg0SQhpHhgAEWA+AFkIVxSACgBKGzjlKJiRBxTvOABeOABmMzs4cziifm9C4ublIhhXKB44PJLlOFk+YAA3S1GxmzK6CpwwJdV1LXM4FH4F6KXKp1aesdk-SZnRgqblY-MgA)
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
#### Typing getDerivedStateFromProps
Before 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.
Here are a few ways in which you can annotate `getDerivedStateFromProps`
1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it.
```tsx
class Comp extends React.Component<Props, State> {
static getDerivedStateFromProps(
props: Props,
state: State
): Partial<State> | null {
//
}
}
```
2. When you want the function's return value to determine your state.
```tsx
class Comp extends React.Component<
Props,
ReturnType<typeof Comp["getDerivedStateFromProps"]>
> {
static getDerivedStateFromProps(props: Props) {}
}
```
3. When you want derived state with other state fields and memoization
```tsx
type CustomValue = any;
interface Props {
propA: CustomValue;
}
interface DefinedState {
otherStateField: string;
}
type State = DefinedState & ReturnType<typeof transformPropsToState>;
function transformPropsToState(props: Props) {
return {
savedPropA: props.propA, // save for memoization
derivedState: props.propA,
};
}
class Comp extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
otherStateField: "123",
...transformPropsToState(props),
};
}
static getDerivedStateFromProps(props: Props, state: State) {
if (isEqual(props.propA, state.savedPropA)) return null;
return transformPropsToState(props);
}
}
```
[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)
<!--END-SECTION:class-components-->
<!--START-SECTION:default-props-->
#### You May Not Need `defaultProps`
As per [this tweet](https://twitter.com/dan_abramov/status/1133878326358171650), defaultProps will eventually be deprecated. You can check the discussions here:
- [Original tweet](https://twitter.com/hswolff/status/1133759319571345408)
- More info can also be found in [this article](https://medium.com/@matanbobi/react-defaultprops-is-dying-whos-the-contender-443c19d9e7f1)
The consensus is to use object default values.
Function Components:
```tsx
type GreetProps = { age?: number };
const Greet = ({ age = 21 }: GreetProps) => // etc
```
Class Components:
```tsx
type GreetProps = {
age?: number;
};
class Greet extends React.Component<GreetProps> {
render() {
const { age = 21 } = this.props;
/*...*/
}
}
let el = <Greet age={3} />;
```
#### Typing `defaultProps`
Type 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).
**Function Components**
```tsx
// using typeof as a shortcut; note that it hoists!
// you can also declare the type of DefaultProps if you choose
// e.g. https://github.com/typescript-cheatsheets/react/issues/415#issuecomment-841223219
type GreetProps = { age: number } & typeof defaultProps;
const defaultProps = {
age: 21,
};
const Greet = (props: GreetProps) => {
// etc
};
Greet.defaultProps = defaultProps;
```
_[See this in TS Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAOKVYwAKxY6ALxwA3igDmWAFxwAdgFcQAIyxQ4AXzgAyOM1YQCcACZYCyeQBte-VPVwRZqeCbOXrEAXGEi6cCdLgAJgBGABo6dXo6e0d4TixuLzgACjAbGXjuPg9UAEovAD5RXzhKGHkoWTgAHiNgADcCkTScgDpkSTgAeiQFZVVELvVqrrrGiPpMmFaXcytsz2FZtwXbOiA)_
For **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:
```tsx
type GreetProps = typeof Greet.defaultProps & {
age: number;
};
class Greet extends React.Component<GreetProps> {
static defaultProps = {
age: 21,
};
/*...*/
}
// Type-checks! No type assertions needed!
let el = <Greet age={3} />;
```
<details>
<summary><b><code>React.JSX.LibraryManagedAttributes</code> nuance for library authors</b></summary>
The 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`.
The 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:
```tsx
// internal contract, should not be exported out
type GreetProps = {
age: number;
};
class Greet extends Component<GreetProps> {
static defaultProps = { age: 21 };
}
// external contract
export type ApparentGreetProps = React.JSX.LibraryManagedAttributes<
typeof Greet,
GreetProps
>;
```
This will work properly, although hovering over`ApparentGreetProps`may be a little intimidating. You can reduce this boilerplate with the`ComponentProps` utility detailed below.
</details>
#### Consuming Props of a Component with defaultProps
A component with `defaultProps` may seem to have some required props that actually aren't.
##### Problem Statement
Here's what you want to do:
```tsx
interface IProps {
name: string;
}
const defaultProps = {
age: 25,
};
const GreetComponent = ({ name, age }: IProps & typeof defaultProps) => (
<div>{`Hello, my name is ${name}, ${age}`}</div>
);
GreetComponent.defaultProps = defaultProps;
const TestComponent = (props: React.ComponentProps<typeof GreetComponent>) => {
return <h1 />;
};
// Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
const el = <TestComponent name="foo" />;
```
##### Solution
Define a utility that applies `React.JSX.LibraryManagedAttributes`:
```tsx
type ComponentProps<T> = T extends
| React.ComponentType<infer P>
| React.Component<infer P>
? React.JSX.LibraryManagedAttributes<T, P>
: never;
const TestComponent = (props: ComponentProps<typeof GreetComponent>) => {
return <h1 />;
};
// No error
const el = <TestComponent name="foo" />;
```
[_See this in TS Playground_](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAMImQB2W3MABWJhUAHgAqAPjgBeOOLhYAHjD4ATdNjwwAdJ3ARe-cSyyjg3AlihwB0gD6Yqu-Tz4xzl67cl04cAH44ACkAZQANHQAZYAAjKGQoJgBZZG5kAHMsNQBBGBgoOIBXVTFxABofPzgALjheADdrejoLVSgCPDYASSEIETgAb2r0kCw61AKLDPoAXzpcQ0m4NSxOooAbQWF0OWH-TPG4ACYAVnK6WfpF7mWAcUosGFdDd1k4AApB+uQxysO4LM6r0dnAAGRwZisCAEFZrZCbbb9VAASlk0g+1VEamADUkgwABgAJLAbDYQSogJg-MZwYDoAAkg1GWFmlSZh1mBNmogA9Di8XQUfQHlgni8jLpVustn0BnJpQjZTsWrzeXANsh2gwbstxFhJhK3nIPmAdnUjfw5WIoVgYXBReKuK9+JI0TJpPs4JQYEUoNw4KIABYARjgvN8VwYargADkIIooMQoAslvBSe8JAbns7JTSsDIyAQIBAyOHJDQgA)
#### Misc Discussions and Knowledge
<details>
<summary><b>Why does <code>React.FC</code> break <code>defaultProps</code>?</b></summary>
You can check the discussions here:
- https://medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680
- https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30695
- https://github.com/typescript-cheatsheets/react/issues/87
This is just the current state and may be fixed in future.
</details>
<details>
<summary><b>TypeScript 2.9 and earlier</b></summary>
For TypeScript 2.9 and earlier, there's more than one way to do it, but this is the best advice we've yet seen:
```ts
type Props = Required<typeof MyComponent.defaultProps> & {
/* additional props here */
};
export class MyComponent extends React.Component<Props> {
static defaultProps = {
foo: "foo",
};
}
```
Our 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!
```ts
interface IMyComponentProps {
firstProp?: string;
secondProp: IPerson[];
}
export class MyComponent extends React.Component<IMyComponentProps> {
public static defaultProps: Partial<IMyComponentProps> = {
firstProp: "default",
};
}
```
The 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.
[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57) and [here](https://github.com/typescript-cheatsheets/react/issues/61).
</details>
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
<!--END-SECTION:default-props-->
<!--START-SECTION:basic-type-examples-->
#### Typing Component Props
This is intended as a basic orientation and reference for React developers familiarizing with TypeScript.
#### Basic Prop Types Examples
A list of TypeScript types you will likely use in a React+TypeScript app:
```tsx
type AppProps = {
message: string;
count: number;
disabled: boolean;
/** array of a type! */
names: string[];
/** string literals to specify exact string values, with a union type to join them together */
status: "waiting" | "success";
/** an object with known properties (but could have more at runtime) */
obj: {
id: string;
title: string;
};
/** array of objects! (common) */
objArr: {
id: string;
title: string;
}[];
/** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */
obj2: object;
/** an interface with no required properties - (NOT COMMON, except for things like `React.Component<{}, State>`) */
obj3: {};
/** a dict object with any number of properties of the same type */
dict1: {
[key: string]: MyTypeHere;
};
dict2: Record<string, MyTypeHere>; // equivalent to dict1
/** function that doesn't take or return anything (VERY COMMON) */
onClick: () => void;
/** function with named prop (VERY COMMON) */
onChange: (id: number) => void;
/** function type syntax that takes an event (VERY COMMON) */
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
/** alternative function type syntax that takes an event (VERY COMMON) */
onClick(event: React.MouseEvent<HTMLButtonElement>): void;
/** any function as long as you don't invoke it (not recommended) */
onSomething: Function;
/** an optional prop (VERY COMMON!) */
optional?: OptionalType;
/** 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 */
setState: React.Dispatch<React.SetStateAction<number>>;
};
```
##### `object` as the non-primitive type
`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`.
Typing "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.
##### Empty interface, `{}` and `Object`
An 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/).
```ts
interface AnyNonNullishValue {} // equivalent to `type AnyNonNullishValue = {}` or `type AnyNonNullishValue = Object`
let value: AnyNonNullishValue;
// these are all fine, but might not be expected
value = 1;
value = "foo";
value = () => alert("foo");
value = {};
value = { foo: "bar" };
// these are errors
value = undefined;
value = null;
```
#### Useful React Prop Type Examples
Relevant for components that accept other React components as props.
```tsx
export declare interface AppProps {
children?: React.ReactNode; // best, accepts everything React can render
childrenElement: React.JSX.Element; // A single React element
style?: React.CSSProperties; // to pass through style props
onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target
// more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring
props: Props & React.ComponentPropsWithoutRef<"button">; // to impersonate all the props of a button element and explicitly not forwarding its ref
props2: Props & React.ComponentPropsWithRef<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref
}
```
<details>
<summary><b>Small <code>React.ReactNode</code> edge case before React 18</b></summary>
Before the [React 18 type updates](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210), this code typechecked but had a runtime error:
```tsx
type Props = {
children?: React.ReactNode;
};
function Comp({ children }: Props) {
return <div>{children}</div>;
}
function App() {
// Before React 18: Runtime error "Objects are not valid as a React child"
// After React 18: Typecheck error "Type '{}' is not assignable to type 'ReactNode'"
return <Comp>{{}}</Comp>;
}
```
This is because `ReactNode` includes `ReactFragment` which allowed type `{}` before React 18.
[Thanks @pomle for raising this.](https://github.com/typescript-cheatsheets/react/issues/357)
</details>
<details>
<summary><b>React.JSX.Element vs React.ReactNode?</b></summary>
Quote [@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.
- `React.JSX.Element` -> Return value of `React.createElement`
- `React.ReactNode` -> Return value of a component
</details>
[More discussion: Where ReactNode does not overlap with React.JSX.Element](https://github.com/typescript-cheatsheets/react/issues/129)
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
#### Types or Interfaces?
You can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use?
##### TL;DR
Use Interface until You Need Type - [orta](https://twitter.com/orta/status/1356129195835973632?s=20).
##### More Advice
Here's a helpful rule of thumb:
- 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.
- consider using `type` for your React Component Props and State, for consistency and because it is more constrained.
You 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).
The 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).
> 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)
Types 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.
##### Useful table for Types vs Interfaces
It's a nuanced topic, don't get too hung up on it. Here's a handy table:
| Aspect | Type | Interface |
| ----------------------------------------------- | :--: | :-------: |
| Can describe functions | ✅ | ✅ |
| Can describe constructors | ✅ | ✅ |
| Can describe tuples | ✅ | ✅ |
| Interfaces can extend it | ⚠️ | ✅ |
| Classes can extend it | 🚫 | ✅ |
| Classes can implement it (`implements`) | ⚠️ | ✅ |
| Can intersect another one of its kind | ✅ | ⚠️ |
| Can create a union with another one of its kind | ✅ | 🚫 |
| Can be used to create mapped types | ✅ | 🚫 |
| Can be mapped over with mapped types | ✅ | ✅ |
| Expands in error messages and logs | ✅ | 🚫 |
| Can be augmented | 🚫 | ✅ |
| Can be recursive | ⚠️ | ✅ |
⚠️ In some cases
(source: [Karol Majewski](https://twitter.com/karoljmajewski/status/1082413696075382785))
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
<!--END-SECTION:basic-type-examples-->
<!--START-SECTION:get-derived-state-from-props-->
## getDerivedStateFromProps
Before 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.
Here are a few ways in which you can annotate `getDerivedStateFromProps`
1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it.
```tsx
class Comp extends React.Component<Props, State> {
static getDerivedStateFromProps(
props: Props,
state: State
): Partial<State> | null {
//
}
}
```
2. When you want the function's return value to determine your state.
```tsx
class Comp extends React.Component<
Props,
ReturnType<typeof Comp["getDerivedStateFromProps"]>
> {
static getDerivedStateFromProps(props: Props) {}
}
```
3. When you want derived state with other state fields and memoization
```tsx
type CustomValue = any;
interface Props {
propA: CustomValue;
}
interface DefinedState {
otherStateField: string;
}
type State = DefinedState & ReturnType<typeof transformPropsToState>;
function transformPropsToState(props: Props) {
return {
savedPropA: props.propA, // save for memoization
derivedState: props.propA,
};
}
class Comp extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
otherStateField: "123",
...transformPropsToState(props),
};
}
static getDerivedStateFromProps(props: Props, state: State) {
if (isEqual(props.propA, state.savedPropA)) return null;
return transformPropsToState(props);
}
}
```
[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)
<!--END-SECTION:get-derived-state-from-props-->
<!--START-SECTION:forms-and-events-->
#### Forms and Events
If 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):
```tsx
const el = (
<button
onClick={(event) => {
/* event will be correctly typed automatically! */
}}
/>
);
```
But 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:
```tsx
type State = {
text: string;
};
class App extends React.Component<Props, State> {
state = {
text: "",
};
// typing on RIGHT hand side of =
onChange = (e: React.FormEvent<HTMLInputElement>): void => {
this.setState({ text: e.currentTarget.value });
};
render() {
return (
<div>
<input type="text" value={this.state.text} onChange={this.onChange} />
</div>
);
}
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2KA9Drg8IcMDjB1tcblwBccOjCjAeAcwDcmlRQB8W8ovso3HAAvL6KilYwtgBE0R7ulH5wepYAnmBOznAQPIgAkgDiABIAKnAAFij8dsB8SNmYIZo5YpUu9aEAFEi2QhgiAGLQIACiAG4ysqUAsgAyeTxgAK4wI9RIIDJeAJS2YxC1IT5KFjDlwHQidEgwAMowgUidSpacUewiaEtQRDwwJSgoM4biIxihqEt6iptglFCpYXBfnUoJ1tmFwkQYN9cp0LIpZHxgGMvHjwrInMt4DB0khgtFItE4GCIbSlGcLlcHtwRJEVNkeK0qsDgmzzpcWm1gXydCSkuE4LIdITiRYYR4KCogA)
Instead 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_):
```tsx
// typing on LEFT hand side of =
onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
this.setState({text: e.currentTarget.value})
}
```
<details>
<summary><b>Why two ways to do the same thing?</b></summary>
The 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).
</details>
> 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.
**Typing onSubmit, with Uncontrolled components in a Form**
If 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:
```tsx
<form
ref={formRef}
onSubmit={(e: React.SyntheticEvent) => {
e.preventDefault();
const target = e.target as typeof e.target & {
email: { value: string };
password: { value: string };
};
const email = target.email.value; // typechecks!
const password = target.password.value; // typechecks!
// etc...
}}
>
<div>
<label>
Email:
<input type="email" name="email" />
</label>
</div>
<div>
<label>
Password:
<input type="password" name="password" />
</label>
</div>
<div>
<input type="submit" value="Log in" />
</div>
</form>
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtCAOwGctoRlM4BeRYmAOgFc6kLABQBKClVoM4AMSbs4o9gD4FFOHAA8mJmrhFMbAN7aozJJgC+u2gGVeAIxDAYRoUgBcndDxsBPGjAAFkgwwGgAogBuSAEiynCGuupI3GBE0QEAIuYovAA2MKIA3Elw1PTwMChQAOYh8ilVtfUodHAwvmBIEKyN1XXwAGQJpckgKMB5noZwkSh5vB5wDFDANDVwFiXk6rtwYK10AO7QACbTs-OLnitrG1ulDzu75VJI45PyTQPc7xN53DmCyQRTgAHowe1Okg0ME0ABrOgAQlKr3gBzoxzOX36IVShxOUFOgKuIPBkI6XVhMMRKOe6ghcBCaG4rN0Fis5CUug0p2AkW59M0eRQ9iQeUFe3U4Q+U1GmjWYF4lWhbAARH9Jmq4DQUCAkOrNXltWDJbsNGCRWKJTywXyBTz7Wb1BoreLnbsAAoEs7ueUaRXKqFddUYrFE7W6-Whn0R8Eei1um3PC1Ox38hOBlUhtV0BxOGDaoGLdUAGQgGzWJrNqYzFAtJhAgpEQA)
Of 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.
##### List of event types
| Event Type | Description |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AnimationEvent | CSS Animations. |
| ChangeEvent | Changing the value of `<input>`, `<select>` and `<textarea>` element. |
| ClipboardEvent | Using copy, paste and cut events. |
| 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) |
| DragEvent | Drag and drop interaction with a pointer device (e.g. mouse). |
| FocusEvent | Event that occurs when elements gets or loses focus. |
| FormEvent | Event that occurs whenever a form or form element gets/loses focus, a form element value is changed or the form is submitted. |
| InvalidEvent | Fired when validity restrictions of an input fails (e.g `<input type="number" max="10">` and someone would insert number 20). |
| KeyboardEvent | User interaction with the keyboard. Each event describes a single key interaction. |
| InputEvent | Event that occurs before the value of `<input>`, `<select>` and `<textarea>` changes. |
| MouseEvent | Events that occur due to the user interacting with a pointing device (e.g. mouse) |
| 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. |
| TouchEvent | Events that occur due to the user interacting with a touch device. Extends UIEvent. |
| TransitionEvent | CSS Transition. Not fully browser supported. Extends UIEvent |
| UIEvent | Base Event for Mouse, Touch and Pointer events. |
| WheelEvent | Scrolling on a mouse wheel or similar input device. (Note: `wheel` event should not be confused with the `scroll` event) |
| SyntheticEvent | The base event for all above events. Should be used when unsure about event type |
<!--END-SECTION:forms-and-events-->
<!--START-SECTION:context-->
#### Context
#### Basic example
Here's a basic example of creating a context containing the active theme.
```tsx
import { createContext } from "react";
type ThemeContextType = "light" | "dark";
const ThemeContext = createContext<ThemeContextType>("light");
```
Wrap the components that need the context with a context provider:
```tsx
import { useState } from "react";
const App = () => {
const [theme, setTheme] = useState<ThemeContextType>("light");
return (
<ThemeContext.Provider value={theme}>
<MyComponent />
</ThemeContext.Provider>
);
};
```
Call `useContext` to read and subscribe to the context.
```tsx
import { useContext } from "react";
const MyComponent = () => {
const theme = useContext(ThemeContext);
return <p>The current theme is {theme}.</p>;
};
```
#### Without default context value
If you don't have any meaningful default value, specify `null`:
```tsx
import { createContext } from "react";
interface CurrentUserContextType {
username: string;
}
const CurrentUserContext = createContext<CurrentUserContextType | null>(null);
```
```tsx
const App = () => {
const [currentUser, setCurrentUser] = useState<CurrentUserContextType>({
username: "filiptammergard",
});
return (
<CurrentUserContext.Provider value={currentUser}>
<MyComponent />
</CurrentUserContext.Provider>
);
};
```
Now 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`:
```tsx
import { useContext } from "react";
const MyComponent = () => {
const currentUser = useContext(CurrentUserContext);
return <p>Name: {currentUser?.username}.</p>;
};
```
However, 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:
```tsx
import { createContext } from "react";
interface CurrentUserContextType {
username: string;
}
const CurrentUserContext = createContext<CurrentUserContextType | null>(null);
const useCurrentUser = () => {
const currentUserContext = useContext(CurrentUserContext);
if (!currentUserContext) {
throw new Error(
"useCurrentUser has to be used within <CurrentUserContext.Provider>"
);
}
return currentUserContext;
};
```
Using 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`:
```tsx
import { useContext } from "react";
const MyComponent = () => {
const currentUser = useCurrentUser();
return <p>Username: {currentUser.username}.</p>;
};
```
##### Type assertion as an alternative
Another way to avoid having to check for `null` is to use type assertion to tell TypeScript you know the context is not `null`:
```tsx
import { useContext } from "react";
const MyComponent = () => {
const currentUser = useContext(CurrentUserContext);
return <p>Name: {currentUser!.username}.</p>;
};
```
Another option is to use an empty object as default value and cast it to the expected context type:
```tsx
const CurrentUserContext = createContext<CurrentUserContextType>(
{} as CurrentUserContextType
);
```
You can also use non-null assertion to get the same result:
```tsx
const CurrentUserContext = createContext<CurrentUserContextType>(null!);
```
When you don't know what to choose, prefer runtime checking and throwing over type asserting.
<!--END-SECTION:context-->
<!--START-SECTION:forward-create-ref-->
#### forwardRef/createRef
For `useRef`, check the [Hooks section](/docs/basic/getting-started/hooks#useref).
#### Ref as a Prop (Recommended for React 19+)
In React 19+, you can access `ref` directly as a prop in function components - no `forwardRef` wrapper needed.
##### Option 1: Inherit all props from a native element
Use `ComponentPropsWithRef` to inherit all props from a native element.
```tsx
import { ComponentPropsWithRef, useRef } from "react";
function MyInput(props: ComponentPropsWithRef<"input">) {
return <input {...props} />;
}
// Usage in parent component
function Parent() {
const inputRef = useRef<HTMLInputElement>(null);
return <MyInput ref={inputRef} placeholder="Type here..." />;
}
```
##### Option 2: Explicit typing
If you have custom props and want fine-grained control, you can explicitly type the ref:
```tsx
import { Ref, useRef } from "react";
interface MyInputProps {
placeholder: string;
ref: Ref<HTMLInputElement>;
}
function MyInput(props: MyInputProps) {
return <input {...props} />;
}
// Usage in parent component
function Parent() {
const inputRef = useRef<HTMLInputElement>(null);
return <MyInput ref={inputRef} placeholder="Type here..." />;
}
```
**Read more**: [Wrapping/Mirroring a HTML Element](/docs/advanced/patterns_by_usecase#wrappingmirroring-a-html-element)
#### Legacy Approaches (Pre-React 19)
##### forwardRef
For React 18 and earlier, use `forwardRef`:
```tsx
import { forwardRef, ReactNode } from "react";
interface Props {
children?: ReactNode;
type: "submit" | "button";
}
export type Ref = HTMLButtonElement;
export const FancyButton = forwardRef<Ref, Props>((props, ref) => (
<button ref={ref} className="MyClassName" type={props.type}>
{props.children}
</button>
));
```
<details>
<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>
This 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:
```tsx
import { forwardRef, ReactNode, Ref } from "react";
interface Props {
children?: ReactNode;
type: "submit" | "button";
}
export const FancyButton = forwardRef(
(
props: Props,
ref: Ref<HTMLButtonElement> // <-- explicit immutable ref type
) => (
<button ref={ref} className="MyClassName" type={props.type}>
{props.children}
</button>
)
);
```
</details>
If 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).
##### createRef
`createRef` is mostly used for class components. Function components typically rely on `useRef` instead.
```tsx
import { createRef, PureComponent } from "react";
class CssThemeProvider extends PureComponent<Props> {
private rootRef = createRef<HTMLDivElement>();
render() {
return <div ref={this.rootRef}>{this.props.children}</div>;
}
}
```
#### Generic Components with Refs
Generic components typically require manual ref handling since their generic nature prevents automatic type inference. Here are the main approaches:
Read more context in [this article](https://fettblog.eu/typescript-react-generic-forward-refs/).
##### Option 1: Wrapper Component
The most straightforward approach is to manually handle refs through props:
```tsx
interface ClickableListProps<T> {
items: T[];
onSelect: (item: T) => void;
mRef?: React.Ref<HTMLUListElement> | null;
}
export function ClickableList<T>(props: ClickableListProps<T>) {
return (
<ul ref={props.mRef}>
{props.items.map((item, i) => (
<li key={i}>
<button onClick={() => props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}
```
##### Option 2: Redeclare forwardRef
For true `forwardRef` behavior with generics, extend the module declaration:
```tsx
// Redeclare forwardRef to support generics
declare module "react" {
function forwardRef<T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
}
// Now you can use forwardRef with generics normally
import { forwardRef, ForwardedRef } from "react";
interface ClickableListProps<T> {
items: T[];
onSelect: (item: T) => void;
}
function ClickableListInner<T>(
props: ClickableListProps<T>,
ref: ForwardedRef<HTMLUListElement>
) {
return (
<ul ref={ref}>
{props.items.map((item, i) => (
<li key={i}>
<button onClick={() => props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}
export const ClickableList = forwardRef(ClickableListInner);
```
##### Option 3: Call Signature
If you need both generic support and proper forwardRef behavior with full type inference, you can use the call signature:
```tsx
// Add to your type definitions (e.g. in `index.d.ts` file)
interface ForwardRefWithGenerics extends React.FC<WithForwardRefProps<Option>> {
<T extends Option>(props: WithForwardRefProps<T>): ReturnType<
React.FC<WithForwardRefProps<T>>
>;
}
export const ClickableListWithForwardRef: ForwardRefWithGenerics =
forwardRef(ClickableList);
```
Credits: [https://stackoverflow.com/a/73795494](https://stackoverflow.com/a/73795494)
:::note
Option 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.
:::
#### Additional Resources
- [React refs with TypeScript](https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315)
- [Conditional rendering with forwardRef](https://github.com/typescript-cheatsheets/react/issues/167)
---
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new)
<!--END-SECTION:forward-create-ref-->
<!--START-SECTION:portals-->
#### Portals
Using `ReactDOM.createPortal`:
```tsx
const modalRoot = document.getElementById("modal-root") as HTMLElement;
// assuming in your html file has a div with id 'modal-root';
export class Modal extends React.Component<{ children?: React.ReactNode }> {
el: HTMLElement = document.createElement("div");
componentDidMount() {
modalRoot.appendChild(this.el);
}
componentWillUnmount() {
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(this.props.children, this.el);
}
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWRYmAEQHkBZObXAo9GAWgBNcZchTQQAdgGd4ICHxQAbBBAjwAvHAFoAriCRiYAOgDmSGAFF5SXfoBCATwCSfABQAiGXPk8cK1wEo4FAk4AAkAFWYAGQsrPRgAbgoAeiTAiQkdYDEjOCy4OwgtKDgACxgQeTZgS1KgwI1gADc4AHdgGBLcvgIPBW9lGHxE4XIkAA9qeDR5IODmWQU4cZg9PmDkbgMAYVxIMTi4AG8KOCX5AC5QiOjLazUNCG07gzQuFZi7tz4m-2GTuFE4HEcXowD48y0+mcAWO5FOp16igGBhQYDAqy2JWqLg6wAkBiQ8j8w1OAF8KP9AXs4gB1aryACqYhkkJg0KO-wRCyRKgMRBkjSQmOxzlx+MJxP+5JGpyIYj4SCg7Nh8LgRBgRTEtG4TGYLzeSAACtAYApRVj8WAcGB8WgsfI+HKADRwMUEokkuDS0lAA)
<details>
<summary><b>Using hooks</b></summary>
Same as above but using hooks
```tsx
import { useEffect, useRef, ReactNode } from "react";
import { createPortal } from "react-dom";
const modalRoot = document.querySelector("#modal-root") as HTMLElement;
type ModalProps = {
children: ReactNode;
};
function Modal({ children }: ModalProps) {
// create div element only once using ref
const elRef = useRef<HTMLDivElement | null>(null);
if (!elRef.current) elRef.current = document.createElement("div");
useEffect(() => {
const el = elRef.current!; // non-null assertion because it will never be null
modalRoot.appendChild(el);
return () => {
modalRoot.removeChild(el);
};
}, []);
return createPortal(children, elRef.current);
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzkgKIBmZSG2RSyZ2y6MAchACZJwC+cZUEEHADkUVBmEBYAFChIsXHDRiUMJAAVoMFABsefAUNHiYAWnaCp0mQHobcFIUL4QwAHYBzOO7gBPCPhQcAAWMCB6ZMA6XMGODnDswABucADuwDDB3uwiIBy6pgIQMMIA3DJoEG6E8HnsuggQxXAAvAkQaC5IbjAAdACO+EhQvgDKSNEY0AAUAEQAxHUFRTCzAJQOhHAAEgAqALIAMiTRIN0w5dbSML5gXPv5OuoCYFttODJwSsFR7GJuAC5ECY2JxLtxLjIyPg3BhgFU4A96jppng0D8dH9ujwgUjdM8IK8Nh9pF87EoVGoEsk4BMkGcenAqjpfEzYVwiO4vGIyJ8lFUarSdPRWgRiPQADx7I4AEWSJ3p5zgAB84G58DodAA+abqzVrS5fYBkODTACEE3ovU6UH+MA2lqQZGtgTtoosnQZfWUqDUCq9c0SSXWkNJYtIFCoMGm0w2LS1uD5X0q1XgE1FjudNrtZtKcHJbiqpj1ekcxFg8LccAARlQULRvPB0pq1UgksMa1wS0m4EthU0+igwHc3OwAMIY9jTCYGntiGCBKux1oJklfde9x6NYq9MR5dsT37TnSzsNfCF87jYADaAF1T3z54uKb6NFpdNN0b9-thMy7becp7cDIIHSOSRAoB4SCgdCsIwJWcAAILDsua78qmcDXoQwQQKkeI6NgxAwKMOF4Y8t6ikwGC9LQozaGo0xkLoxCnl8T5QEuPYSkGWo9mS9j+PgSgoFWzEQHAYD4PAmTAFsPiCUENSqMAaAhGEERRNBZ7rtxNLAOwLSzH2hQDrMWoSjYPF8bg2G4fhcAAGQOaa1lfBK+G8dpG5uUGrneTUvjRC0OBod5YXUoQYA6CgvhArMHhQPpsyYH5YVRegSAAJJqCAhBxWg5zDMlqXecESDAB4oRxQAjAADLVSTBMVXnhV86TsJkQLCHVDXBMIKUta11boAA1glASjnFUAeMN0y1Zg82Lb01VrM1rVhQAXplo5IAAHkCACcB0Det67cMBg3rp5p1fJlwhCCgm7ImaOCzHAswXTdcAStWUkwAiAVBSFw1oGNAgwuwcVgEOvgoKkPxgB9vBVGOOgqSNwXLvGcBESRdmPIxzFIGs3BamgOgQMQFm-TA-1uNd60WVZl0WR51kk9ZP1-QiKNo6DmNxgmuOkfh0wwFAQwk1qtmpIijzU9z9PWeSYiChAJoKQ4w5cZZyQM2sMjcEAA)
</details>
Modal Component Usage Example:
```tsx
import { useState } from "react";
function App() {
const [showModal, setShowModal] = useState(false);
return (
<div>
// you can also put this in your static html file
<div id="modal-root"></div>
{showModal && (
<Modal>
<div
style={{
display: "grid",
placeItems: "center",
height: "100vh",
width: "100vh",
background: "rgba(0,0,0,0.1)",
zIndex: 99,
}}
>
I'm a modal!{" "}
<button
style={{ background: "papyawhip" }}
onClick={() => setShowModal(false)}
>
close
</button>
</div>
</Modal>
)}
<button onClick={() => setShowModal(true)}>show Modal</button>
// rest of your app
</div>
);
}
```
<details>
<summary><b>Context of Example</b></summary>
This example is based on the [Event Bubbling Through Portal](https://reactjs.org/docs/portals.html#event-bubbling-through-portals) example of React docs.
</details>
<!--END-SECTION:portals-->
<!--START-SECTION:error-boundaries-->
#### Error Boundaries
##### Option 1: Using react-error-boundary
[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.
This approach also lets you avoid class components that are not that popular anymore.
##### Option 2: Writing your custom error boundary component
If you don't want to add a new npm package for this, you can also write your own `ErrorBoundary` component.
```jsx
import React, { Component, ErrorInfo, ReactNode } from "react";
interface Props {
children?: ReactNode;
}
interface State {
hasError: boolean;
}
class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false
};
public static getDerivedStateFromError(_: Error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error("Uncaught error:", error, errorInfo);
}
public render() {
if (this.state.hasError) {
return <h1>Sorry.. there was an error</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
```
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
<!--END-SECTION:error-boundaries-->
<!--START-SECTION:concurrent-->
#### Concurrent React/React Suspense
_Not written yet._ watch <https://github.com/sw-yx/fresh-async-react> for more on React Suspense and Time Slicing.
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
<!--END-SECTION:concurrent-->
<!--START-SECTION:types-->
### Troubleshooting Handbook: Types
> ⚠️ Have you read [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ?) Your answer might be there!
Facing 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!
Try 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.
#### Union Types and Type Guarding
Union types are handy for solving some of these typing problems:
```tsx
class App extends React.Component<
{},
{
count: number | null; // like this
}
> {
state = {
count: null,
};
render() {
return <div onClick={() => this.increment(1)}>{this.state.count}</div>;
}
increment = (amt: number) => {
this.setState((state) => ({
count: (state.count || 0) + amt,
}));
};
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2K0EAK48YALjg89IAEZIocAD6m91agG44AejdxqwANZI4MAAWwHSaKhQAfFrkinQwKNxwALzRijr6hiZmTmHOmkT81gAUAJSpaUQwelA8cLJ8wABucBA8Yt5oPklKpclRQSEiwDxoRCAyRQCMJSoRSgN0InEJSCK6BjAqsm4NjRF5MXDhh8OjSOOGyXBFKCDGDpbWZUlRStoBwYt0SDAAyvHcIrLRIva5vQ5pODrTLXYGraHwWz2AAMZQA1HBbjB3ioSiUDooVAcVEA)
**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:
```ts
interface Admin {
role: string;
}
interface User {
email: string;
}
// Method 1: use `in` keyword
function redirect(user: Admin | User) {
if ("role" in user) {
// use the `in` operator for typeguards since TS 2.7+
routeToAdminPage(user.role);
} else {
routeToHomePage(user.email);
}
}
// Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enough
function isAdmin(user: Admin | User): user is Admin {
return (user as any).role !== undefined;
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoC4AOxiSk3STgEEATEGuAbwrjhwAbJAC44AZxhQaAcwDcFAL5Va9RmmYBVcfR584SECmCCxk6dXlKKFTAFdqGYBGoCIdugBUI7TtQAKKDJIABTiwDLUwJjA9ACUeuT80XBhEVExugC8OQR2OlAIEML4CbxJ-AJIMHZQrvi+NGQVinDWlOT2jjDOrjgeSN4AErhIgcFpkdGxUGX6KZMZM3A5WQSGxoKliZVVNXUEIyBIYEFIzfzK5FcUAPS3cACy1QAWEGxwAIxi+cwABjQ-nAANZIACeAHdoGxbA4nC4qmxgEQMCFflAxI1XAAfODaeI7ODREIAIiESBJRNc6LKcHucF+cBgL3+gLgEDA9BQMGgcEwvJgYM5MjsKCgbHEEhoGjgngAynAAEwAOgA7ABqfT8fpeHwcGjjULo5XkuIKFoGQQ6Qna9y6o5jM5ogrKjYmM36K43cj057M95KsRofI8vCCzlwEVitgAGjgbAgSElzOY4hQxyZL1kVPZgjYunlcAAbvRwi5JbyISyiHAAdQgcBxLQDNR3DIXrDur0ieIsc76Jj9Ti8QU4j8Cj3WEPCUR9q5+1A4ChJShqGC4ibiswAIS5Bz5mLUJAw65AA)
Method 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`.
If 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.
#### Optional Types
If a component has an optional prop, add a question mark and assign during destructure (or use defaultProps).
```tsx
class MyComponent extends React.Component<{
message?: string; // like this
}> {
render() {
const { message = "default" } = this.props;
return <div>{message}</div>;
}
}
```
You can also use a `!` character to assert that something is not undefined, but this is not encouraged.
_Something to add? [File an issue](https://github.com/typescript-cheatsheets/react/issues/new) with your suggestions!_
#### Enum Types
**We recommend avoiding using enums as far as possible**.
Enums 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:
```tsx
export declare type Position = "left" | "right" | "top" | "bottom";
```
If you must use enums, remember that enums in TypeScript default to numbers. You will usually want to use them as strings instead:
```tsx
export enum ButtonSizes {
default = "default",
small = "small",
large = "large",
}
// usage
export const PrimaryButton = (
props: Props & React.HTMLProps<HTMLButtonElement>
) => <Button size={ButtonSizes.default} {...props} />;
```
#### Type Assertion
Sometimes 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.
```tsx
class MyComponent extends React.Component<{
message: string;
}> {
render() {
const { message } = this.props;
return (
<Component2 message={message as SpecialMessageType}>{message}</Component2>
);
}
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgGU61gUAbAWSQGduUBzJABVa9ALwFuMKMAB2-fAG4KFOTCRRM6egAUcYbnADeFOHBA8+ggFxwpM+XAA+cAK6yAJkkxykH5eQAvirkaBCyUnAAwriQskiyMABMtsjoMAB0AGJRADx6EAYAfHASABRG5pYCSIEAlKUlZaZwuR7AAG5FLWa5ABYAjEVGFrw1gbkA9IPd5L2T7V0UdSFobCi8cBzUMeDhCfBIAB7qnoZpGBm7cQe5JnNVYzZ20nL8AYEl92ZEnhplDW+ZjgYQi8Eqoys9ECpTgMD6wG4GTA+m4AWBcCIMFcUFkcGaDwxuWu+0SSUeULEI2qgjgG0YzFYnBpwlEn2pT1qUxJ8TJswxdXRcGCQSAA)
Note 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.
You can also assert a property is non-null, when accessing it:
```ts
element.parentNode!.removeChild(element); // ! before the period
myFunction(document.getElementById(dialog.id!)!); // ! after the property accessing
let userID!: string; // definite assignment assertion... be careful!
```
Of course, try to actually handle the null case instead of asserting :)
#### Simulating Nominal Types
TS' 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):
```ts
type OrderID = string & { readonly brand: unique symbol };
type UserID = string & { readonly brand: unique symbol };
type ID = OrderID | UserID;
```
We can create these values with the Companion Object Pattern:
```ts
function OrderID(id: string) {
return id as OrderID;
}
function UserID(id: string) {
return id as UserID;
}
```
Now TypeScript will disallow you from using the wrong ID in the wrong place:
```ts
function queryForUser(id: UserID) {
// ...
}
queryForUser(OrderID("foobar")); // Error, Argument of type 'OrderID' is not assignable to parameter of type 'UserID'
```
In future you can use the `unique` keyword to brand. [See this PR](https://github.com/microsoft/TypeScript/pull/33038).
#### Intersection Types
Adding two types together can be handy, for example when your component is supposed to mirror the props of a native component like a `button`:
```tsx
export interface PrimaryButtonProps {
label: string;
}
export const PrimaryButton = (
props: PrimaryButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>
) => {
// do custom buttony stuff
return <button {...props}> {props.label} </button>;
};
```
_Playground [here](https://www.typescriptlang.org/play?ssl=4&ssc=1&pln=12&pc=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCipAD0ljmADsYkpN0k4AFKUFKAE8AQgFcYMCE14QwAZzgBvCnDgAbFACMkagFxw5MPkwDmAbgoBfanWjw0Uwzz4gBI8ZKZwAvHAAUKnBgOPL6vPxCYhJSMvJwAGSIxDAAdFGeABIAKgCyADIAghJ8muJIcgA82fnpUgCiakggSCwAfBQAlD6tSoEA9H1wACYQcGiihrhwpdFMggYwopiYgUSLUF4VM55KKXvBsnKWPYoH8ika2mqWcBV921KtFuSWQA)_
You can also use Intersection Types to make reusable subsets of props for similar components:
```tsx
type BaseProps = {
className?: string,
style?: React.CSSProperties
name: string // used in both
}
type DogProps = {
tailsCount: number
}
type HumanProps = {
handsCount: number
}
export const Human = (props: BaseProps & HumanProps) => // ...
export const Dog = (props: BaseProps & DogProps) => // ...
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgCEUBnJABRzGbgF44BvCnGFoANi2YA5FCCQB+AFxxmMKMAB2AcwA0Q4Suqj5S5OhgA6AMIBlaxwh1YwJMz1x1MpEpVqtcAPT+cACurAAmcBpwAEYQMAAWFAC+VLT0ACIQmvZcvAJ6MCjAosyWEMHqMErqwSDRSFDJqXRwABK1KOo53HyC5MLxnWGl5ZXVtfWN5CnkSAAekLBwaBDqKm0d6ibEFgBilgA8TKzdcABkGyCd3QB8eQAUAJS8d-d6B2HAAG4BNxSPFAo80W8BWa3gmU02zM5n2RxY7E43AukNuD2ePFe70+P38f3IjyAA)
Make sure not to confuse Intersection Types (which are **and** operations) with Union Types (which are **or** operations).
#### Union Types
This 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).
The 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.
#### Overloading Function Types
Specifically 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:
```ts
type FunctionType1 = (x: string, y: number) => number;
```
But this doesn't let you do any overloading. If you have the implementation, you can put them after each other with the function keyword:
```ts
function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
function pickCard(x): any {
// implementation with combined signature
// ...
}
```
However, 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`:
```ts
type pickCard = {
(x: { suit: string; card: number }[]): number;
(x: number): { suit: string; card: number };
// no need for combined signature in this form
// you can also type static properties of functions here eg `pickCard.wasCalled`
};
```
Note 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`.
[Read more about Overloading in the Handbook.](https://www.typescriptlang.org/docs/handbook/functions.html#overloads)
#### Using Inferred Types
Leaning 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.
Fortunately, with `typeof`, you won't have to do that. Just use it on any value:
```tsx
const [state, setState] = useState({
foo: 1,
bar: 2,
}); // state's type inferred to be {foo: number, bar: number}
const someMethod = (obj: typeof state) => {
// grabbing the type of state even though it was inferred
// some code using obj
setState(obj); // this works
};
```
#### Using Partial Types
Working 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:
```tsx
const [state, setState] = useState({
foo: 1,
bar: 2,
}); // state's type inferred to be {foo: number, bar: number}
// NOTE: stale state merging is not actually encouraged in useState
// we are just demonstrating how to use Partial here
const partialStateUpdate = (obj: Partial<typeof state>) =>
setState({ ...state, ...obj });
// later on...
partialStateUpdate({ foo: 2 }); // this works
```
<details>
<summary><b>Minor caveats on using <code>Partial</code></b></summary>
Note 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).
</details>
#### The Types I need weren't exported!
This can be annoying but here are ways to grab the types!
- Grabbing the Prop types of a component: Use `React.ComponentProps` and `typeof`, and optionally `Omit` any overlapping types
```tsx
import { Button } from "library"; // but doesn't export ButtonProps! oh no!
type ButtonProps = React.ComponentProps<typeof Button>; // no problem! grab your own!
type AlertButtonProps = Omit<ButtonProps, "onClick">; // modify
const AlertButton = (props: AlertButtonProps) => (
<Button onClick={() => alert("hello")} {...props} />
);
```
You 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)
- Grabbing the return type of a function: use `ReturnType`:
```tsx
// inside some library - return type { baz: number } is inferred but not exported
function foo(bar: string) {
return { baz: 1 };
}
// inside your app, if you need { baz: number }
type FooReturn = ReturnType<typeof foo>; // { baz: number }
```
In 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)
```ts
function foo() {
return {
a: 1,
b: 2,
subInstArr: [
{
c: 3,
d: 4,
},
],
};
}
type InstType = ReturnType<typeof foo>;
type SubInstArr = InstType["subInstArr"];
type SubInstType = SubInstArr[0];
let baz: SubInstType = {
c: 5,
d: 6, // type checks ok!
};
//You could just write a one-liner,
//But please make sure it is forward-readable
//(you can understand it from reading once left-to-right with no jumps)
type SubInstType2 = ReturnType<typeof foo>["subInstArr"][0];
let baz2: SubInstType2 = {
c: 5,
d: 6, // type checks ok!
};
```
- TS also ships with a `Parameters` utility type for extracting the parameters of a function
- 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).
#### The Types I need don't exist!
What's more annoying than modules with unexported types? Modules that are **untyped**!
> 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/)
Fret not! There are more than a couple of ways in which you can solve this problem.
##### Slapping `any` on everything
A **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.
```json
// inside tsconfig.json
{
// ...
"include": [
"src" // automatically resolves if the path to declaration is src/typedec.d.ts
]
// ...
}
```
Within this file, add the `declare` syntax for your desired module, say `my-untyped-module`– to the declaration file:
```ts
// inside typedec.d.ts
declare module "my-untyped-module";
```
This 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.
This 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.
##### Autogenerate types
You can use TypeScript with `--allowJs` and `--declaration` to see TypeScript's "best guess" at the types of the library.
If 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.
```bash
npm install -g dts-gen
dts-gen -m <your-module>
```
There 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).
##### Typing Exported Hooks
Typing Hooks is just like typing pure functions.
The following steps work under two assumptions:
- You have already created a type declaration file as stated earlier in the section.
- 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.
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,
```js
// ...
const useUntypedHook = (prop) => {
// some processing happens here
return {
/* ReturnProps */
};
};
export default useUntypedHook;
```
then, your type declaration should most likely follow the following syntax.
```ts
declare module 'use-untyped-hook' {
export interface InputProps { ... } // type declaration for prop
export interface ReturnProps { ... } // type declaration for return props
export default function useUntypedHook(
prop: InputProps
// ...
): ReturnProps;
}
```
<details>
<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>
```js
// inside src/index.js
const useDarkMode = (
initialValue = false, // -> input props / config props to be exported
{
// -> input props / config props to be exported
element,
classNameDark,
classNameLight,
onChange,
storageKey = "darkMode",
storageProvider,
global,
} = {}
) => {
// ...
return {
// -> return props to be exported
value: state,
enable: useCallback(() => setState(true), [setState]),
disable: useCallback(() => setState(false), [setState]),
toggle: useCallback(() => setState((current) => !current), [setState]),
};
};
export default useDarkMode;
```
As the comments suggest, exporting these config props and return props following the aforementioned structure will result in the following type export.
```ts
declare module "use-dark-mode" {
/**
* A config object allowing you to specify certain aspects of `useDarkMode`
*/
export interface DarkModeConfig {
classNameDark?: string; // A className to set "dark mode". Default = "dark-mode".
classNameLight?: string; // A className to set "light mode". Default = "light-mode".
element?: HTMLElement; // The element to apply the className. Default = `document.body`
onChange?: (val?: boolean) => void; // Override the default className handler with a custom callback.
storageKey?: string; // Specify the `localStorage` key. Default = "darkMode". Set to `null` to disable persistent storage.
storageProvider?: WindowLocalStorage; // A storage provider. Default = `localStorage`.
global?: Window; // The global object. Default = `window`.
}
/**
* An object returned from a call to `useDarkMode`.
*/
export interface DarkMode {
readonly value: boolean;
enable: () => void;
disable: () => void;
toggle: () => void;
}
/**
* A custom React Hook to help you implement a "dark mode" component for your application.
*/
export default function useDarkMode(
initialState?: boolean,
config?: DarkModeConfig
): DarkMode;
}
```
</details>
##### Typing Exported Components
In 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.
For 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.
```ts
declare module "react-router-dom" {
import * as React from 'react';
// ...
type NavigateProps<T> = {
to: string | number,
replace?: boolean,
state?: T
}
//...
export class Navigate<T = any> extends React.Component<NavigateProps<T>>{}
// ...
```
For 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.
#### Frequent Known Problems with TypeScript
Just a list of stuff that React developers frequently run into, that TS has no solution for. Not necessarily TSX only.
##### TypeScript doesn't narrow after an object element null check
[](https://mobile.twitter.com/tannerlinsley/status/1390409931627499523)
Ref: https://mobile.twitter.com/tannerlinsley/status/1390409931627499523. see also https://github.com/microsoft/TypeScript/issues/9998
##### TypeScript doesn't let you restrict the type of children
Guaranteeing typesafety for this kind of API isn't possible:
```tsx
<Menu>
<MenuItem/> {/* ok */}
<MenuLink/> {/* ok */}
<div> {/* error */}
</Menu>
```
Source: https://twitter.com/ryanflorence/status/1085745787982700544?s=20
<!--END-SECTION:types-->
<!--START-SECTION:operators-->
### Troubleshooting Handbook: Operators
- `typeof` and `instanceof`: type query used for refinement
- `keyof`: get keys of an object. `keyof T` is an operator to tell you what values of `k` can be used for `obj[k]`.
- [Some misconceptions here](https://twitter.com/SeaRyanC/status/1418678670739218438?s=20).
- `O[K]`: property lookup
- `[K in O]`: mapped types
- `+` or `-` or `readonly` or `?`: addition and subtraction and readonly and optional modifiers
- `x ? Y : Z`: Conditional types for generic types, type aliases, function parameter types
- `!`: Nonnull assertion for nullable types
- `=`: Generic type parameter default for generic types
- `as`: type assertion
- `is`: type guard for function return types
Conditional Types are a difficult topic to get around so here are some extra resources:
- fully walked through explanation https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/
- Bailing out and other advanced topics https://github.com/sw-yx/ts-spec/blob/master/conditional-types.md
- Basarat's video https://www.youtube.com/watch?v=SbVgPQDealg&list=PLYvdvJlnTOjF6aJsWWAt7kZRJvzw-en8B&index=2&t=0s
- [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ&feature=youtu.be)
<!--END-SECTION:operators-->
<!--START-SECTION:utilities-->
### Troubleshooting Handbook: Utilities
These are all built in, [see source in es5.d.ts](https://github.com/microsoft/TypeScript/blob/33a34e5b96bfe086266f4765ab9789a2a02507f9/src/lib/es5.d.ts#L1523-L1637):
- `Awaited`: emulate the behavior of `await`
- `Capitalize`: convert first character of string literal type to uppercase
- `ConstructorParameters`: a tuple of class constructor's parameter types
- `Exclude`: exclude a type from another type
- `Extract`: select a subtype that is assignable to another type
- `InstanceType`: the instance type you get from a `new`ing a class constructor
- `Lowercase`: convert string literal type to lowercase
- `NonNullable`: exclude `null` and `undefined` from a type
- `Omit`: construct a type with the properties of another type.
- `OmitThisParameter`: remove the 'this' parameter from a function type.
- `Parameters`: a tuple of a function's parameter types
- `Partial`: Make all properties in an object optional
- `Readonly`: Make all properties in an object readonly
- `ReadonlyArray`: Make an immutable array of the given type
- `Pick`: A subtype of an object type with a subset of its keys
- `Record`: A map from a key type to a value type
- `Required`: Make all properties in an object required
- `ReturnType`: A function's return type
- `ThisParameterType`: extract the type of the 'this' parameter of a function type
- `ThisType`: marker for contextual 'this' type
- `Uncapitalize`: convert first character of string literal type to lowercase
- `Uppercase`: convert string literal type to uppercase
<!--END-SECTION:utilities-->
<!--START-SECTION:ts-config-->
### Troubleshooting Handbook: tsconfig.json
You 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`):
```json
{
"compilerOptions": {
"incremental": true,
"outDir": "build/lib",
"target": "es5",
"module": "esnext",
"lib": ["DOM", "ESNext"],
"sourceMap": true,
"importHelpers": true,
"declaration": true,
"rootDir": "src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowJs": false,
"jsx": "react",
"moduleResolution": "node",
"baseUrl": "src",
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "build", "scripts"]
}
```
You can find more [recommended TS config here](https://github.com/tsconfig/bases).
Please open an issue and discuss if there are better recommended choices for React.
Selected flags and why we like them:
- `esModuleInterop`: disables namespace imports (`import * as foo from "foo"`) and enables CJS/AMD/UMD style imports (`import fs from "fs"`)
- `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.
- `"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.
Compilation 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.
<!--END-SECTION:ts-config-->
<!--START-SECTION:official-typings-bugs-->
### Troubleshooting Handbook: Fixing bugs in official typings
If 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`:
```json
{
"compilerOptions": {
"paths": {
"mobx-react": ["../typings/modules/mobx-react"]
}
}
}
```
[Thanks to @adamrackis for the tip.](https://twitter.com/AdamRackis/status/1024827730452520963)
If 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):
```tsx
// my-typings.ts
declare module "plotly.js" {
interface PlotlyHTMLElement {
removeAllListeners(): void;
}
}
// MyComponent.tsx
import { PlotlyHTMLElement } from "plotly.js";
const f = (e: PlotlyHTMLElement) => {
e.removeAllListeners();
};
```
You don't always have to implement the module, you can simply import the module as `any` for a quick start:
```tsx
// my-typings.ts
declare module "plotly.js"; // each of its imports are `any`
```
Because 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.
You can also do ambient variable and ambient type declarations:
```ts
// ambient utility type
type ToArray<T> = T extends unknown[] ? T : T[];
// ambient variable
declare let process: {
env: {
NODE_ENV: "development" | "production";
};
};
process = {
env: {
NODE_ENV: "production",
},
};
```
You can see examples of these included in the built in type declarations in the `lib` field of `tsconfig.json`
<!--END-SECTION:official-typings-bugs-->
<!--START-SECTION:non-ts-files-->
### Troubleshooting Handbook: Globals, Images and other non-TS files
Use [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).
If, say, you are using a third party JS script that attaches on to the `window` global, you can extend `Window`:
```ts
declare global {
interface Window {
MyVendorThing: MyVendorType;
}
}
```
Likewise if you wish to "import" an image or other non TS/TSX file:
```ts
// declaration.d.ts
// anywhere in your project, NOT the same name as any of your .ts/tsx files
declare module "*.png";
// importing in a tsx file
import * as logo from "./logo.png";
```
Note that `tsc` cannot bundle these files for you, you will have to use Webpack or Parcel.
Related issue: https://github.com/Microsoft/TypeScript-React-Starter/issues/12 and [StackOverflow](https://stackoverflow.com/a/49715468/4216035)
<!--END-SECTION:non-ts-files-->
<!--START-SECTION:editor-integration-->
### Editor Tooling and Integration
- VSCode
- swyx's VSCode Extension: https://github.com/sw-yx/swyx-react-typescript-snippets
- amVim: https://marketplace.visualstudio.com/items?itemName=auiworks.amvim
- VIM
- https://github.com/Quramy/tsuquyomi
- nvim-typescript?
- https://github.com/leafgarland/typescript-vim
- peitalin/vim-jsx-typescript
- NeoVim: https://github.com/neoclide/coc.nvim
- other discussion: https://mobile.twitter.com/ryanflorence/status/1085715595994095620
You are free to use this repo's TSX logo if you wish:
[](https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png)
You may also wish to use alternative logos - [jsx-tsx-logos](https://github.com/Protectator/jsx-tsx-logos)

<!--END-SECTION:editor-integration-->
<!--START-SECTION:linting-->
### Linting
> ⚠️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).
> ⚠️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.
Follow the TypeScript + ESLint docs at https://github.com/typescript-eslint/typescript-eslint:
```
yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint
```
add a `lint` script to your `package.json`:
```json
"scripts": {
"lint": "eslint 'src/**/*.ts'"
},
```
and a suitable `.eslintrc.js` (using `.js` over `.json` here so we can add comments):
```js
module.exports = {
env: {
es6: true,
node: true,
jest: true,
},
extends: "eslint:recommended",
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint"],
parserOptions: {
ecmaVersion: 2017,
sourceType: "module",
},
rules: {
indent: ["error", 2],
"linebreak-style": ["error", "unix"],
quotes: ["error", "single"],
"no-console": "warn",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{ vars: "all", args: "after-used", ignoreRestSiblings: false },
],
"@typescript-eslint/explicit-function-return-type": "warn", // Consider using explicit annotations for object literals and function return types even when they can be inferred.
"no-empty": "warn",
},
};
```
Most of this is taken from [the `tsdx` PR](https://github.com/palmerhq/tsdx/pull/70/files) which is for **libraries**.
More `.eslintrc.json` options to consider with more options you may want for **apps**:
```json
{
"extends": [
"airbnb",
"prettier",
"prettier/react",
"plugin:prettier/recommended",
"plugin:jest/recommended",
"plugin:unicorn/recommended"
],
"plugins": ["prettier", "jest", "unicorn"],
"parserOptions": {
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"jest": true
},
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"]
}
}
},
"overrides": [
{
"files": ["**/*.ts", "**/*.tsx"],
"parser": "typescript-eslint-parser",
"rules": {
"no-undef": "off"
}
}
]
}
```
Another 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.
Wes Bos is also working on [TypeScript support for his eslint+prettier config.](https://github.com/wesbos/eslint-config-wesbos/issues/68)
If 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.
<!--END-SECTION:linting-->
<!--START-SECTION:resources-->
### Other React + TypeScript resources
- me! <https://twitter.com/swyx>
- https://www.freecodecamp.org/news/how-to-build-a-todo-app-with-react-typescript-nodejs-and-mongodb/
- <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**.
- [10 Bad TypeScript Habits](https://startup-cto.net/10-bad-typescript-habits-to-break-this-year/):
1. not using `"strict": true`
2. using `||` for default values when we have `??`
3. Using `any` instead of `unknown` for API responses
4. using `as` assertion instead of Type Guards (`function isFoo(obj: unknown): obj is Foo {}`)
5. `as any` in tests
6. Marking optional properties instead of modeling which combinations exist by extending interfaces
7. One letter generics
8. Non-boolean `if (nonboolean)` checks
9. bangbang checks `if (!!nonboolean)`
10. `!= null` to check for `null` and `undefined`
- [Ultimate React Component Patterns with TypeScript 2.8](https://levelup.gitconnected.com/ultimate-react-component-patterns-with-typescript-2-8-82990c516935)
- [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.
- [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)
- [Sindre Sorhus' TypeScript Style Guide](https://github.com/sindresorhus/typescript-definition-style-guide)
- [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.
- [Steve Kinney's React and TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/react-typescript/)
- [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
- [Mike North's Production TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/production-typescript/)
- [TSX Guide](https://jenil.github.io/chota/) by [gojutin](https://github.com/gojutin/www.tsx.guide)
- TypeScript conversion:
- [Lyft's React-To-TypeScript conversion CLI](https://github.com/lyft/react-javascript-to-typescript-transform)
- [Gustav Wengel's blogpost - converting a React codebase to TypeScript](http://www.gustavwengel.dk/converting-typescript-to-javascript-part-1)
- [Microsoft React TypeScript conversion guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide)
- [Matt Pocock's Beginner's Typescript Tutorial](https://github.com/total-typescript/beginners-typescript-tutorial)
- [Matt Pocock's React with TypeScript Tutorial](https://www.totaltypescript.com/tutorials/react-with-typescript)
- [You?](https://github.com/typescript-cheatsheets/react/issues/new).
<!--END-SECTION:resources-->
<!--START-SECTION:talks-->
### Recommended React + TypeScript talks
- [Ultimate React Component Patterns with TypeScript](https://www.youtube.com/watch?v=_PBQ3if6Fmg), by Martin Hochel, GeeCon Prague 2018
- [How to Build React Apps with TypeScript](https://youtu.be/LJzGGmu5APA?si=YNzy7T_8yj7TuXxS), by ClearEdge Tech Talk 2022
- [Create a More Readable React Codebase Using TypeScript](https://youtu.be/nkJbGgieALI?si=IFZZIMEiXz7AsiBv), by Emma Brillhart 2019
- [Advanced TypeScript with React](https://youtu.be/zQfD4ZxxyKA?si=FmrgOq667svX6C9O), by Nikhil Verma 2019
- [Senior Typescript Features You don't Know About - clean-code](https://www.youtube.com/watch?v=Y4u97vJqmhM), by CoderOne 2023
- [React & TypeScript - Course for Beginners](https://www.youtube.com/watch?v=FJDVKeh7RJI), by FreeCodeCamp 2022
- [TypeScript + React](https://www.youtube.com/watch?v=1ZnrX3wiNTU), by Chris Toomey 2019
- [Mastering React Hooks](https://www.youtube.com/watch?v=zM_ZiSl2n2E), by Jack Herrington 2021
- [Using Hooks and codegen](https://www.youtube.com/watch?v=cdsnzfJUqm0) by Tejas Kumar 2019
- Please help contribute to this new section!
<!--END-SECTION:talks-->
<!--START-SECTION:learn-ts-->
### Time to Really Learn TypeScript
Believe 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.
There 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 :)
It is worth mentioning some resources to help you get started:
- Step through the 40+ examples under [the playground's](http://www.typescriptlang.org/play/index.html) Examples section, written by @Orta
- Anders Hejlsberg's overview of TS: https://www.youtube.com/watch?v=ET4kT88JRXs
- Marius Schultz: https://blog.mariusschulz.com/series/typescript-evolution with an [Egghead.io course](https://egghead.io/courses/advanced-static-types-in-typescript)
- Basarat's Deep Dive: https://basarat.gitbook.io/typescript/
- Axel Rauschmeyer's [Tackling TypeScript](https://exploringjs.com/tackling-ts/)
- 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`)
- Learn about [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ&feature=youtu.be)
- Shu Uesugi: [TypeScript for Beginner Programmers](https://ts.chibicode.com/)
- Here is another [TypeScript Error Guide](https://github.com/threehams/typescript-error-guide/) that you can check for your errors.
<!--END-SECTION:learn-ts-->
<!--START-SECTION:examples-->
### Example App
- [Create React App TypeScript Todo Example 2021](https://github.com/laststance/create-react-app-typescript-todo-example-2021)
- [Ben Awad's 14 hour Fullstack React/GraphQL/TypeScript Tutorial](https://www.youtube.com/watch?v=I6ypD7qv3Z8)
- [Cypress Realworld App](https://github.com/cypress-io/cypress-realworld-app)
<!--END-SECTION:examples-->
## My question isn't answered here!
- [File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new).
## Contributors
This 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!
================================================
FILE: code-of-conduct.md
================================================
# Our Code of Conduct
This code of conduct outlines our expectations for participants within
the [typescript-cheatsheets/react](https://github.com/typescript-cheatsheets/react) repository, as well as steps to
reporting unacceptable behavior. We are committed to providing a welcoming and inspiring community for all and expect
our code of conduct to be honored. Anyone who violates this code of conduct may be banned from the community.
Our open source repository strives to:
- **Be friendly and patient.**
- **Be welcoming**: We strive to be a community that welcomes and supports people of all backgrounds and identities.
This includes, but is not limited to members of any race, ethnicity, culture, national origin, colour, immigration
status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age,
size, family status, political belief, religion, and mental and physical ability.
- **Be considerate**: Your work will be used by other people, and you in turn will depend on the work of others. Any
decision you take will affect users and colleagues, and you should take those consequences into account when making
decisions. Remember that we're a world-wide community, so you might not be communicating in someone else's primary
language.
- **Be respectful**: Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor
manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a
personal attack. It’s important to remember that a community where people feel uncomfortable or threatened is not a
productive one.
- **Be careful in the words that you choose**: we are a community of professionals, and we conduct ourselves
professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary
behavior aren't acceptable. This includes, but is not limited to:
- Violent threats or language directed against another person.
- Discriminatory jokes and language.
- Posting sexually explicit or violent material.
- Posting (or threatening to post) other people's personally identifying information ("doxing").
- Personal insults, especially those using racist or sexist terms.
- Unwelcome sexual attention.
- Advocating for, or encouraging, any of the above behavior.
- Repeated harassment of others. In general, if someone asks you to stop, then stop.
- **When we disagree, try to understand why**: Disagreements, both social and technical, happen all the time. It is
important that we resolve disagreements and differing views constructively. Remember that we’re different. The
strength of our community comes from its diversity, people from a wide range of backgrounds. Different people have
different perspectives on issues. Being unable to understand why someone holds a viewpoint doesn’t mean that they’re
wrong. Don’t forget that it is human to err and blaming each other doesn’t get us anywhere. Instead, focus on helping
to resolve issues and learning from mistakes.
This code is not exhaustive or complete. It serves to distill our common understanding of a collaborative, shared
environment, and goals. We expect it to be followed in spirit as much as in the letter.
### Diversity Statement
We encourage everyone to participate and are committed to building a repository for all. Although we may not be able to
satisfy everyone, we all agree that everyone is equal. Whenever a participant has made a mistake, we expect them to take
responsibility for it. If someone has been harmed or offended, it is our responsibility to listen carefully and
respectfully, and do our best to right the wrong.
Although this list cannot be exhaustive, we explicitly honor diversity in age, gender, gender identity or expression,
culture, ethnicity, language, national origin, political beliefs, profession, race, religion, sexual orientation,
socioeconomic status, and technical ability. We will not tolerate discrimination based on any of the protected
characteristics above, including participants with disabilities.
### Reporting Issues
If you experience or witness unacceptable behavior—or have any other concerns—please report it by contacting us (This
repo is maintained by [@swyx](https://twitter.com/swyx), [@eps1lon](https://twitter.com/sebsilbermann)
and [@filiptammergard](https://twitter.com/tammergard).). All reports will be handled with discretion. In your report
please include:
- Your contact information.
- Names (real, nicknames, or pseudonyms) of any individuals involved. If there are additional witnesses, please include
them as well. Your account of what occurred, and if you believe the incident is ongoing. If there is a publicly
available record (e.g. a mailing list archive or a public IRC logger), please include a link.
- Any additional information that may be helpful.
After filing a report, a representative will contact you personally. If the person who is harassing you is part of the
response team, they will recuse themselves from handling your incident. A representative will then review the incident,
follow up with any additional questions, and make a decision as to how to respond. We will respect confidentiality
requests for the purpose of protecting victims of abuse.
Anyone asked to stop unacceptable behavior is expected to comply immediately. If an individual engages in unacceptable
behavior, the representative may take any action they deem appropriate, up to and including a permanent ban from our
community without warning.
## Version
This is version 1.0.0
## Thanks
This code of conduct is based on the [Open Code of Conduct](https://github.com/todogroup/opencodeofconduct) from
the [TODOGroup](http://todogroup.org).
We are thankful for their work and all the communities who have paved the way with code of conducts.
================================================
FILE: copyFile.js
================================================
const fs = require("fs");
const filesTopCopy = [
{
src: "../CONTRIBUTORS.md",
dest: "src/pages/contributors.md",
},
{
src: "../CONTRIBUTING.md",
dest: "src/pages/contributing.md",
},
];
function copyFile(src, dest) {
fs.copyFile(src, dest, (err) => {
if (err) {
console.log("Error Found:", err);
} else {
console.log("Files copied");
}
});
}
filesTopCopy.forEach(({ src, dest }) => {
copyFile(src, dest);
});
================================================
FILE: docs/advanced/index.md
================================================
---
id: intro
sidebar_label: Intro
title: Advanced Cheatsheet
---
**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**.
- It also has miscellaneous tips and tricks for pro users.
- Advice for contributing to DefinitelyTyped
- The goal is to take _full advantage_ of TypeScript.
**Creating React + TypeScript Libraries**
The 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.
Another 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.
- Be sure to also check [`basarat`'s guide](https://basarat.gitbooks.io/typescript/content/docs/quick/library.html) for library tsconfig settings.
- Alec Larson: [The best Rollup config for TypeScript libraries](https://gist.github.com/aleclarson/9900ed2a9a3119d865286b218e14d226)
- From the Angular world, check out https://github.com/bitjson/typescript-starter
================================================
FILE: docs/advanced/misc-concerns.md
================================================
---
id: misc_concerns
title: "Section 3: Misc. Concerns"
sidebar_label: Misc. Concerns
---
Sometimes 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.
## Writing TypeScript Libraries instead of Apps
`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.
```ts
interface MyComponentProps {
autoHeight: boolean;
secondProp: number;
}
export class MyComponent extends React.Component<MyComponentProps, {}> {
static propTypes = {
autoHeight: PropTypes.bool,
secondProp: PropTypes.number.isRequired,
};
}
```
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
## Commenting Components
TypeScript 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.
```tsx
interface MyComponentProps {
/** Description of prop "label".
* @default foobar
* */
label?: string;
}
/**
* General component description in JSDoc format. Markdown is *supported*.
*/
export default function MyComponent({ label = "foobar" }: MyComponentProps) {
return <div>Hello world {label}</div>;
}
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoC4AOxiSk3STgFkBPABRzAGc4BvCnDgB6AFRi4AESQ80UYGBjAI1OBExww3OACIANigBGSfboB0Q4ZIACAEySMArvqwQIRlFCtxJYkVaGJvoA-ABccDwwCtQA5gDcFAC+FBTiYkKSAOJI1PQo+nBouJB5tHAOcgpKKmo0cABSAMpSEGhwmNAgKDDmrF4A1nYQAO51fGI8TmCQsEh2YpbkvgHkSAAes-AOzq4dTtQYtaxsAMIlqrkwABT8cEGmcAC8ep0eXrpwSRHsXBC8AEoBFYiDAnFA1AAeOzAABuAD4ABKmfQQOAjaD6OwCB76JKQkQwhGJchJIA)
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
## Namespaced Components
Often 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()`;
```tsx
import { forwardRef } from "react";
const Input = (props: any) => <input {...props} />;
const Form = forwardRef<HTMLDivElement, any>(
({ children, ...otherProps }, ref) => (
<form {...otherProps} ref={ref}>
{children}
</form>
)
);
/**
* Exported components now can be used as `<Form>` and `<Form.Input>`
*/
export default Object.assign(Form, { Input: Input });
```
[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)
(Contributed by @bryceosterhaus, see [further discussion](https://github.com/typescript-cheatsheets/react/issues/165))
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
## Design System Development
I 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)
For 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 :)
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
## Migrating From Flow
You should check out large projects that are migrating from flow to pick up concerns and tips:
- [Jest](https://github.com/facebook/jest/pull/7554)
- [Expo](https://github.com/expo/expo/issues/2164)
- [React-beautiful-dnd](https://github.com/atlassian/react-beautiful-dnd/issues/982)
- [Storybook](https://github.com/storybooks/storybook/issues/5030)
- [VueJS](https://medium.com/the-vue-point/plans-for-the-next-iteration-of-vue-js-777ffea6fabf)
Useful libraries:
- <https://github.com/bcherny/flow-to-typescript>
- <https://github.com/Khan/flow-to-ts>
- <https://github.com/piotrwitek/utility-types>
If you have specific advice in this area, please file a PR!
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).
## Prettier
There isn't any real secret to Prettier for TypeScript. But its a great idea to run prettier on every commit!
```bash
$ yarn add -D prettier husky lint-staged
```
```json
// inside package.json
{
//...
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"linters": {
"src/*.{ts,tsx,js,jsx,css,scss,md}": [
"prettier --trailing-comma es5 --single-quote --write",
"git add"
],
"ignore": ["**/dist/*, **/node_modules/*"]
}
},
"prettier": {
"printWidth": 80,
"semi": false,
"singleQuote": true,
"trailingComma": "es5"
}
}
```
Integrating 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)
For 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.
## Testing
Yes, you can test your types! You shouldn't use it for EVERYTHING, but it can help prevent regressions:
- https://github.com/azz/jest-runner-tsc
- https://github.com/SamVerschueren/tsd
- https://github.com/ikatyang/dts-jest ([Demo](https://codesandbox.io/s/dts-test-frozen-public-demo-iyorn))
- https://github.com/microsoft/dtslint ([Intro to dtslint](https://www.youtube.com/watch?v=nygcFEwOG8w&feature=share))
## Working with Non-TypeScript Libraries (writing your own index.d.ts)
Lets say you want to use `de-indent`, but it isn't typed or on DefinitelyTyped. You get an error like this:
```
[ts]
Could 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.
Try `npm install @types/de-indent` if it exists or add a new declaration (.d.ts) file containing `declare module 'de-indent';` [7016]
```
So create a `.d.ts` file anywhere in your project with the module definition:
```ts
// de-indent.d.ts
declare module "de-indent" {
function deindent(): void;
export = deindent; // default export
}
```
<details>
<summary>Further Discussion</summary>
Any 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).
</details>
## Compilation Speed
Compiling large TS projects can get slow. Here are some tips:
- We have a dedicated repo tracking TS speed recommendations: https://github.com/typescript-cheatsheets/speed
- Use [TS 3.0 Project references](https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_version#typescript-30)
- 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)
- Webpack ([see CRA diff](https://gist.github.com/jaredpalmer/d3016701589f14df8a3572df91a5754b)):
- set `output.pathinfo = false`
- set `optimization.splitChunks`, `optimization.removeAvailableModules`, `optimization.removeEmptyChunks` to `false`
================================================
FILE: docs/advanced/patterns_by_usecase.md
================================================
---
id: patterns_by_usecase
title: "Useful Patterns by Use Case"
sidebar_label: Useful Patterns by Use Case
---
## Wrapping/Mirroring
### Wrapping/Mirroring a HTML Element
Usecase: you want to make a `<Button>` that takes all the normal props of `<button>` and does extra stuff.
Strategy: extend `React.ComponentPropsWithoutRef<'button'>`
```tsx
// usage
function App() {
// Type '"foo"' is not assignable to type '"button" | "submit" | "reset" | undefined'.(2322)
// return <Button type="foo"> sldkj </Button>
// no error
return <Button type="button"> text </Button>;
}
// implementation
export interface ButtonProps extends React.ComponentPropsWithoutRef<"button"> {
specialProp?: string;
}
export function Button(props: ButtonProps) {
const { specialProp, ...rest } = props;
// do something with specialProp
return <button {...rest} />;
}
```
[_See this in the TS Playground_](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwCwAUI4wPQtwCuqyA5lowQ4A7fMAhC4AQTBgAFAEo4Ab0Zw4bOABUAnmCzkARAQgQDZOMHRCI8NKmA8hyAEYAbfTAhwYu-WQPOHDCeQgZwAD5wBqgcziDAMGGRBpSoWIkRnEIAJlgEwEJY2WQAdLIATADM5eXyqurslDAcUBIAPABCQSHevgC8RiYGAHxwqK7ZANYAVnBtLF3B4sP19RrWcFhQxFD1TS3tiz0+egOBS6GjMFgAHvDzR8uMAL7MDBqgYO4gWEIwyDAxEJGLdILALH8tgQ8PpHkIAArEMDoW7XHLobB4GAlADCJEghT+iIgyLaZHOITIoxUDDUqD0uGAyFcxLAAH4AFxjGBQAo8egMV4MUHQQjCUTiOBw2RgJGoLlw1moRQ0tS4cSoeBKMYMpkspEAGjgJRNqXgzzgfTgspJqAFag02S8qBI6QAFny4AB3BJunVYRnM1l7dIHOYUyVKE0lM0WljDAXPIA)
**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.
<details>
<summary>
Why not `ComponentProps` or `IntrinsicElements` or `[Element]HTMLAttributes` or `HTMLProps` or `HTMLAttributes`?
</summary>
## `ComponentProps`
You 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.
More info: https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/
### Maybe `React.JSX.IntrinsicElements` or `[Element]HTMLAttributes`
There are at least 2 other equivalent ways to do this, but they are more verbose:
```tsx
// Method 1: React.JSX.IntrinsicElements
type BtnType = React.JSX.IntrinsicElements["button"]; // cannot inline or will error
export interface ButtonProps extends BtnType {} // etc
// Method 2: React.[Element]HTMLAttributes
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>
```
Looking 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.
> 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).
Ultimately, [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.
### Definitely not `React.HTMLProps` or `React.HTMLAttributes`
This is what happens when you use `React.HTMLProps`:
```tsx
export interface ButtonProps extends React.HTMLProps<HTMLButtonElement> {
specialProp: string;
}
export function Button(props: ButtonProps) {
const { specialProp, ...rest } = props;
// ERROR: Type 'string' is not assignable to type '"button" | "submit" | "reset" | undefined'.
return <button {...rest} />;
}
```
It 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).
This is what happens when you use `React.HTMLAttributes`:
```tsx
import { HTMLAttributes } from "react";
export interface ButtonProps extends HTMLAttributes<HTMLButtonElement> {
/* etc */
}
function App() {
// Property 'type' does not exist on type 'IntrinsicAttributes & ButtonProps'
return <Button type="submit"> text </Button>;
}
```
</details>
### Wrapping/Mirroring a Component
> TODO: this section needs work to make it simplified.
Usecase: same as above, but for a React Component you don't have access to the underlying props
```tsx
import { CSSProperties } from "react";
const Box = (props: CSSProperties) => <div style={props} />;
const Card = (
{ title, children, ...props }: { title: string } & $ElementProps<typeof Box> // new utility, see below
) => (
<Box {...props}>
{title}: {children}
</Box>
);
```
Strategy: extract a component's props by inferring them
Example:
```tsx
// ReactUtilityTypes.d.ts
declare type $ElementProps<T> = T extends React.ComponentType<infer Props>
? Props extends object
? Props
: never
: never;
```
Usage:
```tsx
import * as Recompose from "recompose";
export const defaultProps = <
C extends React.ComponentType,
D extends Partial<$ElementProps<C>>
>(
defaults: D,
Component: C
): React.ComponentType<$ElementProps<C> & Partial<D>> =>
Recompose.defaultProps(defaults)(Component);
```
_thanks [dmisdm](https://github.com/typescript-cheatsheets/react/issues/23)_
:new: You should also consider whether to explicitly forward refs:
```tsx
import { forwardRef, ReactNode } from "react";
// base button, with ref forwarding
type Props = { children: ReactNode; type: "submit" | "button" };
export type Ref = HTMLButtonElement;
export const FancyButton = forwardRef<Ref, Props>((props, ref) => (
<button ref={ref} className="MyCustomButtonClass" type={props.type}>
{props.children}
</button>
));
```
## Polymorphic Components (e.g. with `as` props)
> "Polymorphic Components" = passing a component to be rendered, e.g. with `as` props
`ElementType` is pretty useful to cover most types that can be passed to createElement e.g.
```tsx
function PassThrough(props: { as: React.ElementType<any> }) {
const { as: Component } = props;
return <Component />;
}
```
You might also see this with React Router:
```tsx
const PrivateRoute = ({ component: Component, ...rest }: PrivateRouteProps) => {
const { isLoggedIn } = useAuth();
return isLoggedIn ? <Component {...rest} /> : <Redirect to="/" />;
};
```
For more info you can refer to these resources:
- https://blog.andrewbran.ch/polymorphic-react-components/
- https://github.com/kripod/react-polymorphic-box
- https://stackoverflow.com/questions/58200824/generic-react-typescript-component-with-as-prop-able-to-render-any-valid-dom
[Thanks @eps1lon](https://github.com/typescript-cheatsheets/react/pull/69) and [@karol-majewski](https://github.com/typescript-cheatsheets/react/issues/151) for thoughts!
## Generic Components
Just 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.
```tsx
import { ReactNode, useState } from "react";
interface Props<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
function List<T>(props: Props<T>) {
const { items, renderItem } = props;
const [state, setState] = useState<T[]>([]); // You can use type T in List function scope.
return (
<div>
{items.map(renderItem)}
<button onClick={() => setState(items)}>Clone</button>
{JSON.stringify(state, null, 2)}
</div>
);
}
```
You can then use the generic components and get nice type safety through type inference:
```tsx
ReactDOM.render(
<List
items={["a", "b"]} // type of 'string' inferred
renderItem={(item) => (
<li key={item}>
{/* Error: Property 'toPrecision' does not exist on type 'string'. */}
{item.toPrecision(3)}
</li>
)}
/>,
document.body
);
```
As of [TS 2.9](#typescript-29), you can also supply the type parameter in your JSX to opt out of type inference:
```tsx
ReactDOM.render(
<List<number>
items={["a", "b"]} // Error: Type 'string' is not assignable to type 'number'.
renderItem={(item) => <li key={item}>{item.toPrecision(3)}</li>}
/>,
document.body
);
```
You can also use Generics using fat arrow function style:
```tsx
import { ReactNode, useState } from "react";
interface Props<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
// Note the <T extends unknown> before the function definition.
// You can't use just `<T>` as it will confuse the TSX parser whether it's a JSX tag or a Generic Declaration.
// You can also use <T,> https://github.com/microsoft/TypeScript/issues/15713#issuecomment-499474386
const List = <T extends unknown>(props: Props<T>) => {
const { items, renderItem } = props;
const [state, setState] = useState<T[]>([]); // You can use type T in List function scope.
return (
<div>
{items.map(renderItem)}
<button onClick={() => setState(items)}>Clone</button>
{JSON.stringify(state, null, 2)}
</div>
);
};
```
The same for using classes: (Credit: [Karol Majewski](https://twitter.com/WrocTypeScript/status/1163234064343736326)'s [gist](https://gist.github.com/karol-majewski/befaf05af73c7cb3248b4e084ae5df71))
```tsx
import { PureComponent, ReactNode } from "react";
interface Props<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
interface State<T> {
items: T[];
}
class List<T> extends PureComponent<Props<T>, State<T>> {
// You can use type T inside List class.
state: Readonly<State<T>> = {
items: [],
};
render() {
const { items, renderItem } = this.props;
// You can use type T inside List class.
const clone: T[] = items.slice(0);
return (
<div>
{items.map(renderItem)}
<button onClick={() => this.setState({ items: clone })}>Clone</button>
{JSON.stringify(this.state, null, 2)}
</div>
);
}
}
```
Though you can't use Generic Type Parameters for Static Members:
```tsx
class List<T> extends React.PureComponent<Props<T>, State<T>> {
// Static members cannot reference class type parameters.ts(2302)
static getDerivedStateFromProps(props: Props<T>, state: State<T>) {
return { items: props.items };
}
}
```
To fix this you need to convert your static function to a type inferred function:
```tsx
class List<T> extends React.PureComponent<Props<T>, State<T>> {
static getDerivedStateFromProps<T>(props: Props<T>, state: State<T>) {
return { items: props.items };
}
}
```
## Typing Children
Some 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.
### What You CAN Do
You can type the **structure** of your children: just one child, or a tuple of children.
The following are valid:
```ts
type OneChild = React.ReactNode;
type TwoChildren = [React.ReactNode, React.ReactNode];
type ArrayOfProps = SomeProp[];
type NumbersChildren = number[];
type TwoNumbersChildren = [number, number];
```
<details>
<summary>
Don't forget that you can also use `prop-types` if TS fails you.
</summary>
```ts
Parent.propTypes = {
children: PropTypes.shape({
props: PropTypes.shape({
// could share `propTypes` to the child
value: PropTypes.string.isRequired,
}),
}).isRequired,
};
```
</details>
### What You CANNOT Do
The 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.
This 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)_)
## Type Narrowing based on Props
What you want:
```tsx
// Usage
function App() {
return (
<>
{/* 😎 All good */}
<Button target="_blank" href="https://www.google.com">
Test
</Button>
{/* 😭 Error, `disabled` doesnt exist on anchor element */}
<Button disabled href="x">
Test
</Button>
</>
);
}
```
How to implement: Use [type guards](https://basarat.gitbook.io/typescript/type-system/typeguard#user-defined-type-guards)!
```tsx
// Button props
type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
href?: undefined;
};
// Anchor props
type AnchorProps = React.AnchorHTMLAttributes<HTMLAnchorElement> & {
href?: string;
};
// Input/output options
type Overload = {
(props: ButtonProps): React.JSX.Element;
(props: AnchorProps): React.JSX.Element;
};
// Guard to check if href exists in props
const hasHref = (props: ButtonProps | AnchorProps): props is AnchorProps =>
"href" in props;
// Component
const Button: Overload = (props: ButtonProps | AnchorProps) => {
// anchor render
if (hasHref(props)) return <a {...props} />;
// button render
return <button {...props} />;
};
```
[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)
Components, 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".
A 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.
```tsx
type ButtonProps = React.JSX.IntrinsicElements["button"];
type AnchorProps = React.JSX.IntrinsicElements["a"];
// optionally use a custom type guard
function isPropsForAnchorElement(
props: ButtonProps | AnchorProps
): props is AnchorProps {
return "href" in props;
}
function Clickable(props: ButtonProps | AnchorProps) {
if (isPropsForAnchorElement(props)) {
return <a {...props} />;
} else {
return <button {...props} />;
}
}
```
They don't even need to be completely different props, as long as they have at least one difference in properties:
```tsx
type LinkProps = Omit<React.JSX.IntrinsicElements["a"], "href"> & {
to?: string;
};
function RouterLink(props: LinkProps | AnchorProps) {
if ("href" in props) {
return <a {...props} />;
} else {
return <Link {...props} />;
}
}
```
<details>
<summary><b>Approach: Generic Components</b></summary>
Here is an example solution, see the further discussion for other solutions. _thanks to [@jpavon](https://github.com/typescript-cheatsheets/react/issues/12#issuecomment-394440577)_
```tsx
interface LinkProps {}
type AnchorProps = React.AnchorHTMLAttributes<HTMLAnchorElement>;
type RouterLinkProps = Omit<NavLinkProps, "href">;
const Link = <T extends {}>(
props: LinkProps & T extends RouterLinkProps ? RouterLinkProps : AnchorProps
) => {
if ((props as RouterLinkProps).to) {
return <NavLink {...(props as RouterLinkProps)} />;
} else {
return <a {...(props as AnchorProps)} />;
}
};
<Link<RouterLinkProps> to="/">My link</Link>; // ok
<Link<AnchorProps> href="/">My link</Link>; // ok
<Link<RouterLinkProps> to="/" href="/">
My link
</Link>; // error
```
</details>
<details>
<summary><b>Approach: Composition</b></summary>
If 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:
```tsx
type AnchorProps = React.AnchorHTMLAttributes<HTMLAnchorElement>;
type RouterLinkProps = Omit<AnchorProps, "href">;
interface ButtonProps {
as: React.ComponentClass | "a";
children?: React.ReactNode;
}
const Button: React.FunctionComponent<ButtonProps> = (props) => {
const { as: Component, children, ...rest } = props;
return (
<Component className="button" {...rest}>
{children}
</Component>
);
};
const AnchorButton: React.FunctionComponent<AnchorProps> = (props) => (
<Button as="a" {...props} />
);
const LinkButton: React.FunctionComponent<RouterLinkProps> = (props) => (
<Button as={NavLink} {...props} />
);
<LinkButton to="/login">Login</LinkButton>;
<AnchorButton href="/login">Login</AnchorButton>;
<AnchorButton href="/login" to="/test">
Login
</AnchorButton>; // Error: Property 'to' does not exist on type...
```
</details>
You 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/).
Here is a brief intuition for **Discriminated Union Types**:
```ts
type UserTextEvent = {
type: "TextEvent";
value: string;
target: HTMLInputElement;
};
type UserMouseEvent = {
type: "MouseEvent";
value: [number, number];
target: HTMLElement;
};
type UserEvent = UserTextEvent | UserMouseEvent;
function handle(event: UserEvent) {
if (event.type === "TextEvent") {
event.value; // string
event.target; // HTMLInputElement
return;
}
event.value; // [number, number]
event.target; // HTMLElement
}
```
<details>
<summary>
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.
</summary>
```ts
type UserTextEvent = { value: string; target: HTMLInputElement };
type UserMouseEvent = { value: [number, number]; target: HTMLElement };
type UserEvent = UserTextEvent | UserMouseEvent;
function handle(event: UserEvent) {
if (typeof event.value === "string") {
event.value; // string
event.target; // HTMLInputElement | HTMLElement (!!!!)
return;
}
event.value; // [number, number]
event.target; // HTMLInputElement | HTMLElement (!!!!)
}
```
The 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)
</details>
<details>
<summary>
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.
<br/><br/>
</summary>
```tsx
import { useMemo } from "react";
interface SingleElement {
isArray: true;
value: string[];
}
interface MultiElement {
isArray: false;
value: string;
}
type Props = SingleElement | MultiElement;
function Sequence(p: Props) {
return useMemo(
() => (
<div>
value(s):
{p.isArray && p.value.join(",")}
{!p.isArray && p.value}
</div>
),
[p.isArray, p.value] // TypeScript automatically matches the corresponding value type based on dependency change
);
}
function App() {
return (
<div>
<Sequence isArray={false} value={"foo"} />
<Sequence isArray={true} value={["foo", "bar", "baz"]} />
</div>
);
}
```
<a href="https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8dccAD5wA3vwETgqAIJQoyJgC44MKAFcs9CRIBuyADYblqVcAB2AcwDaAXRpxxAgL7jhY7QKmz5SuAQOomo66BkZwJlDmFloSTvS4EGYmcAAacDxwABRgypwQ3ACU6QB8ouKUMGpQZphUMAB0aoEAslggEJnBmUU8pZ0ecAA8ACbAOsXB2nqGWJmoBYqTEiJg9V5yCnAAZFtwq9Ma9QBWEOaZZAA0ZAUuAwIiAISr6z7bu-uhWLcegwD0o+NggULsErM8ZBsmBc9vUDlgbNDfr84AAVFhYVC4SJgeDINQwEjIGDAXAGfRMOAgIm4AAWGJUdLgCTkGMgZlGljgcJU6PEBXocToBDUZnwwEScGkYDA3TKAgqVRq-QkIzGTP0aFQADlkCAsDwAERSsAGiYDQZpF4KHgifz6QJOLmfG1kAgQCBkR2-M0-S0Qnw21QaR1wm1WV3uy7kABGyCgUbIsYAXmQbF6fQI-gCffy6E4gA"><i>See this in TS Playground</i>
</a>
In the above example, based on the `isArray` union member, the type of the `value` hook dependency changes.
</details>
To streamline this you may also combine this with the concept of **User-Defined Type Guards**:
```ts
function isString(a: unknown): a is string {
return typeof a === "string";
}
```
[Read more about User-Defined Type Guards in the Handbook](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards).
### Narrowing using `extends`
See this quick guide: https://twitter.com/mpocock1/status/1500813765973053440?s=20&t=ImUA-NnZc4iUuPDx-XiMTA
## Props: One or the other but not both
Since 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:
```tsx
type Props1 = { foo: string; bar?: never };
type Props2 = { bar: string; foo?: never };
const OneOrTheOther = (props: Props1 | Props2) => {
if ("foo" in props && typeof props.foo === "string") {
// `props.bar` is of type `undefined`
return <>{props.foo}</>;
}
// `props.foo` is of type `undefined`
return <>{props.bar}</>;
};
const Component = () => (
<>
<OneOrTheOther /> {/* error */}
<OneOrTheOther foo="" /> {/* ok */}
<OneOrTheOther bar="" /> {/* ok */}
<OneOrTheOther foo="" bar="" /> {/* error */}
</>
);
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOABRzAGcBGOAXjgG85MIIAXHCYwowAHYBzANxwARiigB+IeKQA3JFDgBfaRWq0GEZgCYO3eYqEixU2Xwgq4azdr3k0EcSLgB5NT8oABUACyQ-GHDtTgAKMEYmIWNmNgAfekTTAEoOAD5uUjg4YEw4WPxHfBLxOASTJjgAMia4KhoIMvrmADpHDnZOfFsJSXxcriLiuAB6GbgAA26mHoUoBZLGzrbDRYBXcQATJEwJJEOFqeKiGD2oWoAePK5lvv4dB5m8-WKdKbnFq9HBtgFsyu1aAsDsdTmoLlMbndHs9XmsPl99B4vD54ABhXCQNTieBxXLsAqxKZPK5wB4BCIhcKRaKzApcGYAKjgWhw2g5Mz+01p9KCYQiUS0vH47Hw1S+3E5cAgAGs4PzBdM6YFGeKWWsZXK2YqVWqBTStQyxczJY4DVYoHb5eyuTzoKaNZ88qRstIgA).
A better alternative might be to use a discriminant prop like this:
```tsx
type Props1 = { type: "foo"; foo: string };
type Props2 = { type: "bar"; bar: string };
const OneOrTheOther = (props: Props1 | Props2) => {
if (props.type === "foo") {
// `props.bar` does not exist
return <>{props.foo}</>;
}
// `props.foo` does not exist
return <>{props.bar}</>;
};
const Component = () => (
<>
<OneOrTheOther type="foo" /> {/* error */}
<OneOrTheOther type="foo" foo="" /> {/* ok */}
<OneOrTheOther type="foo" bar="" /> {/* error */}
<OneOrTheOther type="foo" foo="" bar="" /> {/* error */}
<OneOrTheOther type="bar" /> {/* error */}
<OneOrTheOther type="bar" foo="" /> {/* error */}
<OneOrTheOther type="bar" bar="" /> {/* ok */}
<OneOrTheOther type="bar" foo="" bar="" /> {/* error */}
</>
);
```
[View in the TypeScript Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOABRzAGcBGOAXjgG84qaAuApggR8AbjjCIgpjCjAAdgHM4AXzEVqtBhGYAmDt15bB+AEYoo4uBagy5ilevJoIC2XADyCpJ6gAVAAtfGGCoQwAKMEYmQR1mNgAfehi9AEoOAD5uUjg4YEw4KJiAOj5adkqhEXwMrly8uAB6JrgAA2jdJhLbNrgAEwgkJjgFCHgkAA9gWQa8ohgAVygFOAAeTK5O5hKpVTWmzI081QaW9u3uqT7B4dHxuCmZmAaF5dWNrdLbfcONZ1c7ngAGFcJAfAp4JwIhl2NkIg0NnN1t5fAFgp5QkhwuV2PgpPhmtkuE0AFSPKA4cKkpqnRoonx+IIhMLGGh4gmSER4wmHbhkuAQADWcBpdMaa1RTIxWJxWg5NRslh5RP55OxVNFtORksZ6JZ2LZSAVoi5EBVthVfJJ6sp0C14ryurRzMxrNx5ksvOJAo19rFOql+rdho9tkJUitPttmoD9Od0oNcvZnqsSqgUbVgpFcYlQddsqNePDZotyvw3qzfup2qdh1IaTEQA).
## Props: Pass all or nothing
Passing 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":
```tsx
interface All {
a: string;
b: string;
}
type Nothing = Record<string, never>;
const AllOrNothing = (props: All | Nothing) => {
if ("a" in props) {
return <>{props.b}</>;
}
return <>Nothing</>;
};
const Component = () => (
<>
<AllOrNothing /> {/* ok */}
<AllOrNothing a="" /> {/* error */}
<AllOrNothing b="" /> {/* error */}
<AllOrNothing a="" b="" /> {/* ok */}
</>
);
```
While 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:
```tsx
interface Props {
obj?: {
a: string;
b: string;
};
}
const AllOrNothing = (props: Props) => {
if (props.obj) {
return <>{props.obj.a}</>;
}
return <>Nothing</>;
};
const Component = () => (
<>
<AllOrNothing /> {/* ok */}
<AllOrNothing obj={{ a: "" }} /> {/* error */}
<AllOrNothing obj={{ b: "" }} /> {/* error */}
<AllOrNothing obj={{ a: "", b: "" }} /> {/* ok */}
</>
);
```
Another way is to make both props optional and then check that either none or all props are passed at runtime.
## Props: Pass One ONLY IF the Other Is Passed
Say 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).
You 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.
Usage example:
```tsx
const App = () => (
<>
{/* these all typecheck */}
<Text>not truncated</Text>
<Text truncate>truncated</Text>
<Text truncate expanded>
truncate-able but expanded
</Text>
{/* TS error: Property 'truncate' is missing in type '{ children: string; expanded: true; }' but required in type '{ truncate: true; expanded?: boolean | undefined; }'. */}
<Text expanded>truncate-able but expanded</Text>
</>
);
```
You can implement this by function overloads:
```tsx
import { ReactNode } from "react";
interface CommonProps {
children?: ReactNode;
miscProps?: any;
}
type NoTruncateProps = CommonProps & { truncate?: false };
type TruncateProps = CommonProps & { truncate: true; expanded?: boolean };
// Function overloads to accept both prop types NoTruncateProps & TruncateProps
function Text(props: NoTruncateProps): React.JSX.Element;
function Text(props: TruncateProps): React.JSX.Element;
function Text(props: CommonProps & { truncate?: boolean; expanded?: boolean }) {
const { children, truncate, expanded, ...otherProps } = props;
const classNames = truncate ? ".truncate" : "";
return (
<div className={classNames} aria-expanded={!!expanded} {...otherProps}>
{children}
</
gitextract_e6_naeoq/
├── .all-contributorsrc
├── .dockerignore
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── advanced-cheatsheet.md
│ │ ├── basic-cheatsheet.md
│ │ ├── general-react-ts-question.md
│ │ ├── hoc-cheatsheet.md
│ │ └── migrating-cheatsheet.md
│ ├── pull_request_template.md
│ ├── stale.yml
│ └── workflows/
│ ├── main.yml
│ └── mlc_config.json
├── .gitignore
├── .husky/
│ └── pre-commit
├── .nvmrc
├── CONTRIBUTING.md
├── CONTRIBUTORS.md
├── LICENSE
├── README.md
├── code-of-conduct.md
├── copyFile.js
├── docs/
│ ├── advanced/
│ │ ├── index.md
│ │ ├── misc-concerns.md
│ │ ├── patterns_by_usecase.md
│ │ ├── patterns_by_version.md
│ │ ├── types-react-ap.md
│ │ └── utility-types.md
│ ├── basic/
│ │ ├── editor-integration.md
│ │ ├── examples.md
│ │ ├── getting-started/
│ │ │ ├── basic-type-examples.md
│ │ │ ├── class-components.md
│ │ │ ├── concurrent.md
│ │ │ ├── context.md
│ │ │ ├── default-props.md
│ │ │ ├── error-boundaries.md
│ │ │ ├── forms-and-events.md
│ │ │ ├── forward-create-ref.md
│ │ │ ├── function-components.md
│ │ │ ├── hooks.md
│ │ │ └── portals.md
│ │ ├── linting.md
│ │ ├── recommended/
│ │ │ ├── codebases.md
│ │ │ ├── resources.md
│ │ │ └── talks.md
│ │ ├── setup.md
│ │ └── troubleshooting/
│ │ ├── learn-ts.md
│ │ ├── non-ts-files.md
│ │ ├── official-typings-bugs.md
│ │ ├── operators.md
│ │ ├── ts-config.md
│ │ ├── types.md
│ │ └── utilities.md
│ ├── hoc/
│ │ ├── excluding-props.md
│ │ ├── full-example.md
│ │ ├── index.md
│ │ └── react-hoc-docs.md
│ ├── migration/
│ │ ├── from-flow.md
│ │ ├── from-js.md
│ │ ├── index.md
│ │ └── js-docs.md
│ └── react-types/
│ ├── ComponentProps.md
│ ├── ReactNode.md
│ └── index.md
├── genReadme.js
├── netlify.toml
├── package.json
└── website/
├── README.md
├── docusaurus.config.js
├── package.json
├── sidebars.json
└── src/
├── css/
│ └── custom.css
└── pages/
├── help.js
├── index.js
└── users.js
SYMBOL INDEX (11 symbols across 5 files)
FILE: copyFile.js
function copyFile (line 13) | function copyFile(src, dest) {
FILE: genReadme.js
function readContentFromPath (line 25) | async function readContentFromPath(relativePath) {
function updateSectionWith (line 38) | async function updateSectionWith(options) {
function withHeadingContext (line 92) | function withHeadingContext(relativeHeadingLevel, markdown) {
function generateContentForSection (line 98) | function generateContentForSection(options) {
function getFenceForSection (line 133) | function getFenceForSection(readme, sectionName, isToc = false) {
function getFence (line 148) | function getFence(sectionName, isToc = false) {
function main (line 155) | async function main(argv) {
FILE: website/src/pages/help.js
function Help (line 14) | function Help() {
FILE: website/src/pages/index.js
function Home (line 8) | function Home() {
FILE: website/src/pages/users.js
function Users (line 6) | function Users() {
Condensed preview — 73 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (438K chars).
[
{
"path": ".all-contributorsrc",
"chars": 6637,
"preview": "{\n \"files\": [\n \"CONTRIBUTORS.md\",\n \"README.md\"\n ],\n \"imageSize\": 100,\n \"commit\": true,\n \"commitConvention\": \""
},
{
"path": ".dockerignore",
"chars": 21,
"preview": "*/node_modules\n*.log\n"
},
{
"path": ".github/ISSUE_TEMPLATE/advanced-cheatsheet.md",
"chars": 281,
"preview": "---\nname: Advanced Cheatsheet\nabout: Report Issue/Suggest an idea for Advanced Cheatsheet\ntitle: \"[Advanced] ISSUE_TITLE"
},
{
"path": ".github/ISSUE_TEMPLATE/basic-cheatsheet.md",
"chars": 484,
"preview": "---\nname: Basic Cheatsheet\nabout: Report Issue/Suggest an idea for Basic Cheatsheet\ntitle: \"[Basic] ISSUE_TITLE_HERE\"\nla"
},
{
"path": ".github/ISSUE_TEMPLATE/general-react-ts-question.md",
"chars": 411,
"preview": "---\nname: General React+TS Question\nabout: Questions are welcome! We want to know and solve your pain points.\ntitle: \"[Q"
},
{
"path": ".github/ISSUE_TEMPLATE/hoc-cheatsheet.md",
"chars": 256,
"preview": "---\nname: HOC Cheatsheet\nabout: Report Issue/Suggest an idea for HOC Cheatsheet\ntitle: \"[HOC] ISSUE_TITLE_HERE\"\nlabels: "
},
{
"path": ".github/ISSUE_TEMPLATE/migrating-cheatsheet.md",
"chars": 286,
"preview": "---\nname: Migrating Cheatsheet\nabout: Report Issue/Suggest an idea for Migrating Cheatsheet\ntitle: \"[Migrating] ISSUE_TI"
},
{
"path": ".github/pull_request_template.md",
"chars": 419,
"preview": "Thanks for contributing!\n\n- **If you are making a significant PR**, please make sure there is an open issue first\n- **If"
},
{
"path": ".github/stale.yml",
"chars": 684,
"preview": "# Number of days of inactivity before an issue becomes stale\ndaysUntilStale: 60\n# Number of days of inactivity before a "
},
{
"path": ".github/workflows/main.yml",
"chars": 631,
"preview": "name: CI\non:\n push:\n branches: [main]\n pull_request:\n branches: [main]\n\njobs:\n files-up-to-date:\n runs-on: u"
},
{
"path": ".github/workflows/mlc_config.json",
"chars": 37,
"preview": "{\n \"aliveStatusCodes\": [200, 429]\n}\n"
},
{
"path": ".gitignore",
"chars": 2115,
"preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs."
},
{
"path": ".husky/pre-commit",
"chars": 69,
"preview": "#!/bin/sh\n. \"$(dirname \"$0\")/_/husky.sh\"\n\nyarn pretty-quick --staged\n"
},
{
"path": ".nvmrc",
"chars": 5,
"preview": "20.x\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 2525,
"preview": "# Let's Contribute Together! 🚀\n\nWe appreciate your interest in contributing to this project. Here are some core principl"
},
{
"path": "CONTRIBUTORS.md",
"chars": 10635,
"preview": "## Contributors\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start "
},
{
"path": "LICENSE",
"chars": 1067,
"preview": "MIT License\n\nCopyright (c) 2018 shawn wang\n\nPermission is hereby granted, free of charge, to any person obtaining a copy"
},
{
"path": "README.md",
"chars": 125790,
"preview": "# React TypeScript Cheatsheet\n\nCheatsheet for using React with TypeScript.\n\n---\n\n<a href=\"https://github.com/typescript-"
},
{
"path": "code-of-conduct.md",
"chars": 5918,
"preview": "# Our Code of Conduct\n\nThis code of conduct outlines our expectations for participants within\nthe [typescript-cheatsheet"
},
{
"path": "copyFile.js",
"chars": 465,
"preview": "const fs = require(\"fs\");\nconst filesTopCopy = [\n {\n src: \"../CONTRIBUTORS.md\",\n dest: \"src/pages/contributors.md"
},
{
"path": "docs/advanced/index.md",
"chars": 1454,
"preview": "---\nid: intro\nsidebar_label: Intro\ntitle: Advanced Cheatsheet\n---\n\n**This Advanced Cheatsheet** helps show and explain a"
},
{
"path": "docs/advanced/misc-concerns.md",
"chars": 8312,
"preview": "---\nid: misc_concerns\ntitle: \"Section 3: Misc. Concerns\"\nsidebar_label: Misc. Concerns\n---\n\nSometimes writing React isn'"
},
{
"path": "docs/advanced/patterns_by_usecase.md",
"chars": 35609,
"preview": "---\nid: patterns_by_usecase\ntitle: \"Useful Patterns by Use Case\"\nsidebar_label: Useful Patterns by Use Case\n---\n\n## Wrap"
},
{
"path": "docs/advanced/patterns_by_version.md",
"chars": 18479,
"preview": "---\nid: patterns_by_version\ntitle: \"Useful Patterns by TypeScript Version\"\nsidebar_label: Useful Patterns by TypeScript "
},
{
"path": "docs/advanced/types-react-ap.md",
"chars": 7539,
"preview": "---\nid: types_react_api\ntitle: \"Section 4: @types/react and @types/react-dom APIs\"\nsidebar_label: \"@types/react and @typ"
},
{
"path": "docs/advanced/utility-types.md",
"chars": 954,
"preview": "---\nid: utility_types\ntitle: \"Utility Types\"\nsidebar_label: Utility Types\n---\n\nWe will assume knowledge of utility types"
},
{
"path": "docs/basic/editor-integration.md",
"chars": 1141,
"preview": "---\nid: editor_integration\ntitle: Editor Tooling and Integration\n---\n\n- VSCode\n - swyx's VSCode Extension: https://gith"
},
{
"path": "docs/basic/examples.md",
"chars": 383,
"preview": "---\nid: examples\ntitle: Example App\nsidebar_label: Examples\n---\n\n- [Create React App TypeScript Todo Example 2021](https"
},
{
"path": "docs/basic/getting-started/basic-type-examples.md",
"chars": 8563,
"preview": "---\nid: basic_type_example\ntitle: Typing Component Props\n---\n\nThis is intended as a basic orientation and reference for "
},
{
"path": "docs/basic/getting-started/class-components.md",
"chars": 6807,
"preview": "---\nid: class_components\ntitle: Class Components\n---\n\nWithin TypeScript, `React.Component` is a generic type (aka `React"
},
{
"path": "docs/basic/getting-started/concurrent.md",
"chars": 274,
"preview": "---\nid: concurrent\ntitle: Concurrent React/React Suspense\n---\n\n_Not written yet._ watch <https://github.com/sw-yx/fresh-"
},
{
"path": "docs/basic/getting-started/context.md",
"chars": 3714,
"preview": "---\nid: context\ntitle: Context\n---\n\n## Basic example\n\nHere's a basic example of creating a context containing the active"
},
{
"path": "docs/basic/getting-started/default-props.md",
"chars": 7273,
"preview": "---\nid: default_props\ntitle: Typing defaultProps\n---\n\n## You May Not Need `defaultProps`\n\nAs per [this tweet](https://tw"
},
{
"path": "docs/basic/getting-started/error-boundaries.md",
"chars": 1339,
"preview": "---\nid: error_boundaries\ntitle: Error Boundaries\n---\n\n### Option 1: Using react-error-boundary\n\n[React-error-boundary](h"
},
{
"path": "docs/basic/getting-started/forms-and-events.md",
"chars": 10019,
"preview": "---\nid: forms_and_events\ntitle: Forms and Events\n---\n\nIf performance is not an issue (and it usually isn't!), inlining h"
},
{
"path": "docs/basic/getting-started/forward-create-ref.md",
"chars": 6073,
"preview": "---\nid: forward_and_create_ref\ntitle: forwardRef/createRef\n---\n\nFor `useRef`, check the [Hooks section](/docs/basic/gett"
},
{
"path": "docs/basic/getting-started/function-components.md",
"chars": 4792,
"preview": "---\nid: function_components\ntitle: Function Components\n---\n\nThese can be written as normal functions that take a `props`"
},
{
"path": "docs/basic/getting-started/hooks.md",
"chars": 15353,
"preview": "---\nid: hooks\ntitle: Hooks\n---\n\nHooks are [supported in `@types/react` from v16.8 up](https://github.com/DefinitelyTyped"
},
{
"path": "docs/basic/getting-started/portals.md",
"chars": 4443,
"preview": "---\nid: portals\ntitle: Portals\n---\n\nUsing `ReactDOM.createPortal`:\n\n```tsx\nconst modalRoot = document.getElementById(\"mo"
},
{
"path": "docs/basic/linting.md",
"chars": 3340,
"preview": "---\nid: linting\ntitle: Linting\n---\n\n> ⚠️Note that [TSLint is now in maintenance and you should try to use ESLint instead"
},
{
"path": "docs/basic/recommended/codebases.md",
"chars": 2777,
"preview": "---\nid: codebases\ntitle: Recommended React + TypeScript codebases to learn from\nsidebar_label: Codebases\n---\n\n- Apps\n -"
},
{
"path": "docs/basic/recommended/resources.md",
"chars": 3298,
"preview": "---\nid: resources\ntitle: Other React + TypeScript resources\nsidebar_label: Other resources\n---\n\n- me! <https://twitter.c"
},
{
"path": "docs/basic/recommended/talks.md",
"chars": 1151,
"preview": "---\nid: talks\ntitle: Recommended React + TypeScript talks\nsidebar_label: Talks\n---\n\n- [Ultimate React Component Patterns"
},
{
"path": "docs/basic/setup.md",
"chars": 1847,
"preview": "---\nid: setup\ntitle: Setup\n---\n\n## Prerequisites\n\nYou can use this cheatsheet for reference at any skill level, but basi"
},
{
"path": "docs/basic/troubleshooting/learn-ts.md",
"chars": 1775,
"preview": "---\nid: learn_ts\ntitle: \"Time to Really Learn TypeScript\"\nsidebar_label: Time to Really Learn TypeScript\n---\n\nBelieve it"
},
{
"path": "docs/basic/troubleshooting/non-ts-files.md",
"chars": 956,
"preview": "---\nid: non_ts_files\ntitle: \"Troubleshooting Handbook: Globals, Images and other non-TS files\"\nsidebar_label: Globals, I"
},
{
"path": "docs/basic/troubleshooting/official-typings-bugs.md",
"chars": 1978,
"preview": "---\nid: official_typings_bugs\ntitle: Fixing bugs in official typings\nsidebar_label: Fixing bugs in official typings\n---\n"
},
{
"path": "docs/basic/troubleshooting/operators.md",
"chars": 1301,
"preview": "---\nid: operators\ntitle: \"Troubleshooting Handbook: Operators\"\nsidebar_label: Operators\n---\n\n- `typeof` and `instanceof`"
},
{
"path": "docs/basic/troubleshooting/ts-config.md",
"chars": 2418,
"preview": "---\nid: tsconfig\ntitle: \"Troubleshooting Handbook: tsconfig.json\"\nsidebar_label: tsconfig.json\n---\n\nYou can find [all th"
},
{
"path": "docs/basic/troubleshooting/types.md",
"chars": 23350,
"preview": "---\nid: types\ntitle: \"Troubleshooting Handbook: Types\"\nsidebar_label: Types\n---\n\n> ⚠️ Have you read [the TypeScript FAQ]"
},
{
"path": "docs/basic/troubleshooting/utilities.md",
"chars": 1603,
"preview": "---\nid: utilities\ntitle: \"Troubleshooting Handbook: Utilities\"\nsidebar_label: Utilities\n---\n\nThese are all built in, [se"
},
{
"path": "docs/hoc/excluding-props.md",
"chars": 7531,
"preview": "---\nid: excluding_props\nsidebar_label: Excluding Props\ntitle: \"Section 2: Excluding Props\"\n---\n\nThis is covered in passi"
},
{
"path": "docs/hoc/full-example.md",
"chars": 3928,
"preview": "---\nid: full_example\nsidebar_label: Full HOC Example\ntitle: \"Full HOC Example\"\n---\n\n> This is an HOC example for you to "
},
{
"path": "docs/hoc/index.md",
"chars": 2340,
"preview": "---\nid: intro\nsidebar_label: Intro\ntitle: HOC Cheatsheet\n---\n\n**This HOC Cheatsheet** compiles all available knowledge f"
},
{
"path": "docs/hoc/react-hoc-docs.md",
"chars": 12021,
"preview": "---\nid: react_hoc_docs\nsidebar_label: React HOC docs in TypeScript\ntitle: \"Section 1: React HOC docs in TypeScript\"\n---\n"
},
{
"path": "docs/migration/from-flow.md",
"chars": 1608,
"preview": "---\nid: from_flow\ntitle: From Flow\n---\n\n- (2022) Try Stripe's [Flow to TS codemod](https://github.com/stripe-archive/flo"
},
{
"path": "docs/migration/from-js.md",
"chars": 5290,
"preview": "---\nid: from_js\ntitle: From JS\n---\n\n## Automated JS to TS Conversion\n\n- [TypeStat](https://github.com/JoshuaKGoldberg/Ty"
},
{
"path": "docs/migration/index.md",
"chars": 9368,
"preview": "---\nid: intro\nsidebar_label: Intro\ntitle: Migrating (to TypeScript) Cheatsheet\n---\n\nThis Cheatsheet collates advice and "
},
{
"path": "docs/migration/js-docs.md",
"chars": 887,
"preview": "---\nid: js_docs\ntitle: JSDoc\n---\n\n- https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript\n- webpack's"
},
{
"path": "docs/react-types/ComponentProps.md",
"chars": 2383,
"preview": "---\ntitle: ComponentProps<ElementType>\n---\n\n`ComponentProps<ElementType>` constructs a type with all valid props of an e"
},
{
"path": "docs/react-types/ReactNode.md",
"chars": 899,
"preview": "---\ntitle: ReactNode\n---\n\n`ReactNode` is a type that describes what React can render.\n\n## Parameters\n\n`ReactNode` does n"
},
{
"path": "docs/react-types/index.md",
"chars": 289,
"preview": "---\ntitle: React Types\n---\n\n`@types/react` makes some types available that can be very useful. Here's a list in alphabet"
},
{
"path": "genReadme.js",
"chars": 10111,
"preview": "const fs = require(\"fs/promises\");\nconst path = require(\"path\");\nconst Fm = require(\"front-matter\");\nconst Toc = require"
},
{
"path": "netlify.toml",
"chars": 612,
"preview": "[build]\n # Directory to change to before starting a build.\n # This is where we will look for package.json/.nvmrc/etc.\n"
},
{
"path": "package.json",
"chars": 1082,
"preview": "{\n \"name\": \"react-typescript-cheatsheet\",\n \"version\": \"1.0.0\",\n \"description\": \"this package.json is just for mainten"
},
{
"path": "website/README.md",
"chars": 721,
"preview": "# Website\n\nThis website is built using [Docusaurus 2](https://v2.docusaurus.io/), a modern static website generator.\n\n##"
},
{
"path": "website/docusaurus.config.js",
"chars": 5655,
"preview": "const { themes } = require(\"prism-react-renderer\");\n\n// List of projects/orgs using your project for the users page.\ncon"
},
{
"path": "website/package.json",
"chars": 735,
"preview": "{\n \"scripts\": {\n \"add-pages-on-site\": \"node ../copyFile.js\",\n \"start\": \"yarn add-pages-on-site && docusaurus star"
},
{
"path": "website/sidebars.json",
"chars": 1942,
"preview": "{\n \"docs\": {\n \"Basic\": [\n \"basic/setup\",\n {\n \"type\": \"category\",\n \"label\": \"Getting Started\""
},
{
"path": "website/src/css/custom.css",
"chars": 1276,
"preview": ":root {\n --ifm-color-primary: #138cd3;\n --ifm-color-primary-dark: #117ebe;\n --ifm-color-primary-darker: #1077b3;\n --"
},
{
"path": "website/src/pages/help.js",
"chars": 1499,
"preview": "import React from \"react\";\nimport useDocusaurusContext from \"@docusaurus/useDocusaurusContext\";\nimport useBaseUrl from \""
},
{
"path": "website/src/pages/index.js",
"chars": 1258,
"preview": "import React from \"react\";\nimport Link from \"@docusaurus/Link\";\nimport useDocusaurusContext from \"@docusaurus/useDocusau"
},
{
"path": "website/src/pages/users.js",
"chars": 1505,
"preview": "import React from \"react\";\nimport useDocusaurusContext from \"@docusaurus/useDocusaurusContext\";\nimport Layout from \"@the"
}
]
About this extraction
This page contains the full source code of the typescript-cheatsheets/react GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 73 files (410.1 KB), approximately 120.1k tokens, and a symbol index with 11 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.