{"id":13403241,"url":"https://github.com/typescript-cheatsheets/react","last_synced_at":"2025-05-15T00:04:59.182Z","repository":{"id":37315189,"uuid":"135786093","full_name":"typescript-cheatsheets/react","owner":"typescript-cheatsheets","description":"Cheatsheets for experienced React developers getting started with TypeScript","archived":false,"fork":false,"pushed_at":"2025-01-11T19:37:08.000Z","size":3134,"stargazers_count":46243,"open_issues_count":1,"forks_count":4200,"subscribers_count":393,"default_branch":"main","last_synced_at":"2025-05-07T23:35:44.311Z","etag":null,"topics":["cheatsheet","guide","react","typescript"],"latest_commit_sha":null,"homepage":"https://react-typescript-cheatsheet.netlify.app","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/typescript-cheatsheets.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"code-of-conduct.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-06-02T04:08:16.000Z","updated_at":"2025-05-07T20:56:08.000Z","dependencies_parsed_at":"2024-03-26T12:47:27.082Z","dependency_job_id":"c122ab91-1e28-4c81-a6b3-126316f4690c","html_url":"https://github.com/typescript-cheatsheets/react","commit_stats":{"total_commits":939,"total_committers":205,"mean_commits":4.580487804878048,"dds":0.610223642172524,"last_synced_commit":"6b69a322f4854862a0fa1f4562b0d5c829225817"},"previous_names":["typescript-cheatsheets/react-typescript-cheatsheet","sw-yx/react-typescript-cheatsheet"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/typescript-cheatsheets","download_url":"https://codeload.github.com/typescript-cheatsheets/react/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253871702,"owners_count":21976741,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","guide","react","typescript"],"created_at":"2024-07-30T19:01:27.260Z","updated_at":"2025-05-15T00:04:59.016Z","avatar_url":"https://github.com/typescript-cheatsheets.png","language":"JavaScript","readme":"# React TypeScript Cheatsheet\n\nCheatsheet for using React with TypeScript.\n\n---\n\n\u003ca href=\"https://github.com/typescript-cheatsheets/react/issues/81\"\u003e\n  \u003cimg\n    height=\"90\"\n    width=\"90\"\n    alt=\"react + ts logo\"\n    src=\"https://user-images.githubusercontent.com/84442212/194379444-02e5ec69-5e6c-4100-bd7a-c31d628af29c.png\"\n    align=\"left\"\n  /\u003e\n\u003c/a\u003e\n\n[**Web docs**](https://react-typescript-cheatsheet.netlify.app/docs/basic/setup) |\n[Contribute!](https://github.com/typescript-cheatsheets/react/blob/main/CONTRIBUTING.md) |\n[Ask!](https://github.com/typescript-cheatsheets/react/issues/new/choose)\n\n:wave: This repo is maintained by [@eps1lon](https://twitter.com/sebsilbermann) and [@filiptammergard](https://twitter.com/tammergard). We're so happy you want to try out React with TypeScript! If you see anything wrong or missing, please [file an issue](https://github.com/typescript-cheatsheets/react/issues/new/choose)! :+1:\n\n---\n\n[![All Contributors](https://img.shields.io/github/contributors/typescript-cheatsheets/react-typescript-cheatsheet?color=orange\u0026style=flat-square)](/CONTRIBUTORS.md) | [![Discord](https://img.shields.io/discord/508357248330760243.svg?label=\u0026logo=discord\u0026logoColor=ffffff\u0026color=7389D8\u0026labelColor=6A7EC2)](https://discord.gg/wTGS5z9)\n\n- [The Basic Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/basic/setup) is focused on helping React devs just start using TS in React **apps**\n  - Focus on opinionated best practices, copy+pastable examples.\n  - Explains some basic TS types usage and setup along the way.\n  - Answers the most Frequently Asked Questions.\n  - Does not cover generic type logic in detail. Instead we prefer to teach simple troubleshooting techniques for newbies.\n  - The goal is to get effective with TS without learning _too much_ TS.\n- [The Advanced Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/advanced) helps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+React **libraries**.\n  - It also has miscellaneous tips and tricks for pro users.\n  - Advice for contributing to DefinitelyTyped.\n  - The goal is to take _full advantage_ of TypeScript.\n- [The Migrating Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/migration) helps collate advice for incrementally migrating large codebases from JS or Flow, **from people who have done it**.\n  - We do not try to convince people to switch, only to help people who have already decided.\n  - ⚠️This is a new cheatsheet, all assistance is welcome.\n- [The HOC Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/hoc) specifically teaches people to write HOCs with examples.\n  - Familiarity with [Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html) is necessary.\n  - ⚠️This is the newest cheatsheet, all assistance is welcome.\n\n---\n\n## Basic Cheatsheet\n\n### Basic Cheatsheet Table of Contents\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003eExpand Table of Contents\u003c/b\u003e\u003c/summary\u003e\n\n- [React TypeScript Cheatsheet](#react-typescript-cheatsheet)\n  - [Basic Cheatsheet](#basic-cheatsheet)\n    - [Basic Cheatsheet Table of Contents](#basic-cheatsheet-table-of-contents)\n    - [Section 1: Setup](#section-1-setup)\n      - [Prerequisites](#prerequisites)\n      - [React and TypeScript starter kits](#react-and-typescript-starter-kits)\n      - [Try React and TypeScript online](#try-react-and-typescript-online)\n    - [Section 2: Getting Started](#section-2-getting-started)\n      - [Function Components](#function-components)\n      - [Hooks](#hooks)\n      - [useState](#usestate)\n      - [useCallback](#usecallback)\n      - [useReducer](#usereducer)\n      - [useEffect / useLayoutEffect](#useeffect--uselayouteffect)\n      - [useRef](#useref)\n        - [Option 1: DOM element ref](#option-1-dom-element-ref)\n        - [Option 2: Mutable value ref](#option-2-mutable-value-ref)\n        - [See also](#see-also)\n      - [useImperativeHandle](#useimperativehandle)\n        - [See also:](#see-also-1)\n      - [Custom Hooks](#custom-hooks)\n      - [More Hooks + TypeScript reading:](#more-hooks--typescript-reading)\n      - [Example React Hooks + TypeScript Libraries:](#example-react-hooks--typescript-libraries)\n      - [Class Components](#class-components)\n      - [Typing getDerivedStateFromProps](#typing-getderivedstatefromprops)\n      - [You May Not Need `defaultProps`](#you-may-not-need-defaultprops)\n      - [Typing `defaultProps`](#typing-defaultprops)\n      - [Consuming Props of a Component with defaultProps](#consuming-props-of-a-component-with-defaultprops)\n        - [Problem Statement](#problem-statement)\n        - [Solution](#solution)\n      - [Misc Discussions and Knowledge](#misc-discussions-and-knowledge)\n      - [Typing Component Props](#typing-component-props)\n      - [Basic Prop Types Examples](#basic-prop-types-examples)\n        - [`object` as the non-primitive type](#object-as-the-non-primitive-type)\n        - [Empty interface, `{}` and `Object`](#empty-interface--and-object)\n      - [Useful React Prop Type Examples](#useful-react-prop-type-examples)\n      - [Types or Interfaces?](#types-or-interfaces)\n        - [TL;DR](#tldr)\n        - [More Advice](#more-advice)\n        - [Useful table for Types vs Interfaces](#useful-table-for-types-vs-interfaces)\n  - [getDerivedStateFromProps](#getderivedstatefromprops)\n    - [Forms and Events](#forms-and-events)\n      - [List of event types](#list-of-event-types)\n    - [Context](#context)\n    - [Basic example](#basic-example)\n    - [Without default context value](#without-default-context-value)\n      - [Type assertion as an alternative](#type-assertion-as-an-alternative)\n    - [forwardRef/createRef](#forwardrefcreateref)\n    - [Generic forwardRefs](#generic-forwardrefs)\n      - [Option 1 - Wrapper component](#option-1---wrapper-component)\n      - [Option 2 - Redeclare forwardRef](#option-2---redeclare-forwardref)\n      - [Option 3 - Call signature](#option-3---call-signature)\n    - [More Info](#more-info)\n    - [Portals](#portals)\n    - [Error Boundaries](#error-boundaries)\n      - [Option 1: Using react-error-boundary](#option-1-using-react-error-boundary)\n      - [Option 2: Writing your custom error boundary component](#option-2-writing-your-custom-error-boundary-component)\n    - [Concurrent React/React Suspense](#concurrent-reactreact-suspense)\n    - [Troubleshooting Handbook: Types](#troubleshooting-handbook-types)\n      - [Union Types and Type Guarding](#union-types-and-type-guarding)\n      - [Optional Types](#optional-types)\n      - [Enum Types](#enum-types)\n      - [Type Assertion](#type-assertion)\n      - [Simulating Nominal Types](#simulating-nominal-types)\n      - [Intersection Types](#intersection-types)\n      - [Union Types](#union-types)\n      - [Overloading Function Types](#overloading-function-types)\n      - [Using Inferred Types](#using-inferred-types)\n      - [Using Partial Types](#using-partial-types)\n      - [The Types I need weren't exported!](#the-types-i-need-werent-exported)\n      - [The Types I need don't exist!](#the-types-i-need-dont-exist)\n        - [Slapping `any` on everything](#slapping-any-on-everything)\n        - [Autogenerate types](#autogenerate-types)\n        - [Typing Exported Hooks](#typing-exported-hooks)\n        - [Typing Exported Components](#typing-exported-components)\n      - [Frequent Known Problems with TypeScript](#frequent-known-problems-with-typescript)\n        - [TypeScript doesn't narrow after an object element null check](#typescript-doesnt-narrow-after-an-object-element-null-check)\n        - [TypeScript doesn't let you restrict the type of children](#typescript-doesnt-let-you-restrict-the-type-of-children)\n    - [Troubleshooting Handbook: Operators](#troubleshooting-handbook-operators)\n    - [Troubleshooting Handbook: Utilities](#troubleshooting-handbook-utilities)\n    - [Troubleshooting Handbook: tsconfig.json](#troubleshooting-handbook-tsconfigjson)\n    - [Troubleshooting Handbook: Fixing bugs in official typings](#troubleshooting-handbook-fixing-bugs-in-official-typings)\n    - [Troubleshooting Handbook: Globals, Images and other non-TS files](#troubleshooting-handbook-globals-images-and-other-non-ts-files)\n    - [Editor Tooling and Integration](#editor-tooling-and-integration)\n    - [Linting](#linting)\n    - [Other React + TypeScript resources](#other-react--typescript-resources)\n    - [Recommended React + TypeScript talks](#recommended-react--typescript-talks)\n    - [Time to Really Learn TypeScript](#time-to-really-learn-typescript)\n    - [Example App](#example-app)\n  - [My question isn't answered here!](#my-question-isnt-answered-here)\n  - [Contributors](#contributors)\n\n\u003c/details\u003e\n\n\u003c!--START-SECTION:setup--\u003e\n\n### Section 1: Setup\n\n#### Prerequisites\n\nYou can use this cheatsheet for reference at any skill level, but basic understanding of React and TypeScript is assumed. Here is a list of prerequisites:\n\n- Basic understanding of [React](https://react.dev/).\n- Familiarity with [TypeScript Basics](https://www.typescriptlang.org/docs/handbook/2/basic-types.html) and [Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html).\n\nIn the cheatsheet we assume you are using the latest versions of React and TypeScript.\n\n#### React and TypeScript starter kits\n\nReact has documentation for [how to start a new React project](https://react.dev/learn/start-a-new-react-project) with some of the most popular frameworks. Here's how to start them with TypeScript:\n\n- [Next.js](https://nextjs.org/docs/basic-features/typescript): `npx create-next-app@latest --ts`\n- [Remix](https://remix.run/docs/tutorials/blog): `npx create-remix@latest`\n- [Gatsby](https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/): `npm init gatsby --ts`\n- [Expo](https://docs.expo.dev/guides/typescript/): `npx create-expo-app -t with-typescript`\n\n#### Try React and TypeScript online\n\nThere are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.\n\n- [TypeScript playground](https://www.typescriptlang.org/play?target=8\u0026jsx=4#code/JYWwDg9gTgLgBAbzgVwM4FMDKMCGN0A0KGAogGZnoDG8AvnGVBCHAORTo42sDcAsAChB6AB6RYcKhAB2qeAGEIyafihwAvHAAUASg0A+RILiSZcuAG0pymEQwxFNgLobiWXPi0AGHfyECTNHRyShotXQMjAJM4ABMIKmQQdBUAOhhgGAAbdFcAAwBNJUks4CoAa3RYuAASBGsVegzk1Dy-E1pfQWM4DhhkKGltHpMAHn0RmNGwfSLkErLK6vqlRrhm9FRRgHoZybGAI2QYGBk4GXlSivUECPVDe0cVLQb4AGo4AEYdWgnomJil0WcGS+zgOyOJxkfwBOxhcC6AlogiAA)\n- [StackBlitz](https://stackblitz.com/fork/react-ts)\n- [CodeSandbox](https://ts.react.new/)\n\n\u003c!--END-SECTION:setup--\u003e\n\n### Section 2: Getting Started\n\n\u003c!--START-SECTION:function-components--\u003e\n\n#### Function Components\n\nThese can be written as normal functions that take a `props` argument and return a JSX element.\n\n```tsx\n// Declaring type of props - see \"Typing Component Props\" for more examples\ntype AppProps = {\n  message: string;\n}; /* use `interface` if exporting so that consumers can extend */\n\n// Easiest way to declare a Function Component; return type is inferred.\nconst App = ({ message }: AppProps) =\u003e \u003cdiv\u003e{message}\u003c/div\u003e;\n\n// You can choose to annotate the return type so an error is raised if you accidentally return some other type\nconst App = ({ message }: AppProps): React.JSX.Element =\u003e \u003cdiv\u003e{message}\u003c/div\u003e;\n\n// You can also inline the type declaration; eliminates naming the prop types, but looks repetitive\nconst App = ({ message }: { message: string }) =\u003e \u003cdiv\u003e{message}\u003c/div\u003e;\n\n// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.\n// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.\nconst App: React.FunctionComponent\u003c{ message: string }\u003e = ({ message }) =\u003e (\n  \u003cdiv\u003e{message}\u003c/div\u003e\n);\n// or\nconst App: React.FC\u003cAppProps\u003e = ({ message }) =\u003e \u003cdiv\u003e{message}\u003c/div\u003e;\n```\n\n\u003e Tip: You might use [Paul Shen's VS Code Extension](https://marketplace.visualstudio.com/items?itemName=paulshen.paul-typescript-toolkit) to automate the type destructure declaration (incl a [keyboard shortcut](https://twitter.com/_paulshen/status/1392915279466745857?s=20)).\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003eWhy is \u003ccode\u003eReact.FC\u003c/code\u003e not needed? What about \u003ccode\u003eReact.FunctionComponent\u003c/code\u003e/\u003ccode\u003eReact.VoidFunctionComponent\u003c/code\u003e?\u003c/b\u003e\u003c/summary\u003e\n\nYou may see this in many React+TypeScript codebases:\n\n```tsx\nconst App: React.FunctionComponent\u003c{ message: string }\u003e = ({ message }) =\u003e (\n  \u003cdiv\u003e{message}\u003c/div\u003e\n);\n```\n\nHowever, the general consensus today is that `React.FunctionComponent` (or the shorthand `React.FC`) is not needed. If you're still using React 17 or TypeScript lower than 5.1, it is even [discouraged](https://github.com/facebook/create-react-app/pull/8177). This is a nuanced opinion of course, but if you agree and want to remove `React.FC` from your codebase, you can use [this jscodeshift codemod](https://github.com/gndelia/codemod-replace-react-fc-typescript).\n\nSome differences from the \"normal function\" version:\n\n- `React.FunctionComponent` is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).\n\n- It provides typechecking and autocomplete for static properties like `displayName`, `propTypes`, and `defaultProps`.\n\n  - Note that there are some known issues using `defaultProps` with `React.FunctionComponent`. See [this issue for details](https://github.com/typescript-cheatsheets/react/issues/87). We maintain a separate `defaultProps` section you can also look up.\n\n- Before the [React 18 type updates](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210), `React.FunctionComponent` provided an implicit definition of `children` (see below), which was heavily debated and is one of the reasons [`React.FC` was removed from the Create React App TypeScript template](https://github.com/facebook/create-react-app/pull/8177).\n\n```tsx\n// before React 18 types\nconst Title: React.FunctionComponent\u003c{ title: string }\u003e = ({\n  children,\n  title,\n}) =\u003e \u003cdiv title={title}\u003e{children}\u003c/div\u003e;\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e(Deprecated)\u003cb\u003eUsing \u003ccode\u003eReact.VoidFunctionComponent\u003c/code\u003e or \u003ccode\u003eReact.VFC\u003c/code\u003e instead\u003c/b\u003e\u003c/summary\u003e\n\nIn [@types/react 16.9.48](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643), the `React.VoidFunctionComponent` or `React.VFC` type was added for typing `children` explicitly.\nHowever, please be aware that `React.VFC` and `React.VoidFunctionComponent` were deprecated in React 18 (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/59882), so this interim solution is no longer necessary or recommended in React 18+.\n\nPlease use regular function components or `React.FC` instead.\n\n```ts\ntype Props = { foo: string };\n\n// OK now, in future, error\nconst FunctionComponent: React.FunctionComponent\u003cProps\u003e = ({\n  foo,\n  children,\n}: Props) =\u003e {\n  return (\n    \u003cdiv\u003e\n      {foo} {children}\n    \u003c/div\u003e\n  ); // OK\n};\n\n// Error now, in future, deprecated\nconst VoidFunctionComponent: React.VoidFunctionComponent\u003cProps\u003e = ({\n  foo,\n  children,\n}) =\u003e {\n  return (\n    \u003cdiv\u003e\n      {foo}\n      {children}\n    \u003c/div\u003e\n  );\n};\n```\n\n\u003c/details\u003e\n\n- _In the future_, it may automatically mark props as `readonly`, though that's a moot point if the props object is destructured in the parameter list.\n\nIn most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of `React.FunctionComponent`.\n\n\u003c/details\u003e\n\n\u003c!--END-SECTION:function-components--\u003e\n\n\u003c!--START-SECTION:hooks--\u003e\n\n#### Hooks\n\nHooks are [supported in `@types/react` from v16.8 up](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031).\n\n#### useState\n\nType inference works very well for simple values:\n\n```tsx\nconst [state, setState] = useState(false);\n// `state` is inferred to be a boolean\n// `setState` only takes booleans\n```\n\nSee also the [Using Inferred Types](https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types/#using-inferred-types) section if you need to use a complex type that you've relied on inference for.\n\nHowever, many hooks are initialized with null-ish default values, and you may wonder how to provide types. Explicitly declare the type, and use a union type:\n\n```tsx\nconst [user, setUser] = useState\u003cUser | null\u003e(null);\n\n// later...\nsetUser(newUser);\n```\n\nYou can also use type assertions if a state is initialized soon after setup and always has a value after:\n\n```tsx\nconst [user, setUser] = useState\u003cUser\u003e({} as User);\n\n// later...\nsetUser(newUser);\n```\n\nThis temporarily \"lies\" to the TypeScript compiler that `{}` is of type `User`. You should follow up by setting the `user` state — if you don't, the rest of your code may rely on the fact that `user` is of type `User` and that may lead to runtime errors.\n\n#### useCallback\n\nYou can type the `useCallback` just like any other function.\n\n```ts\nconst memoizedCallback = useCallback(\n  (param1: string, param2: number) =\u003e {\n    console.log(param1, param2)\n    return { ok: true }\n  },\n  [...],\n);\n/**\n * VSCode will show the following type:\n * const memoizedCallback:\n *  (param1: string, param2: number) =\u003e { ok: boolean }\n */\n```\n\nNote that for React \u003c 18, the function signature of `useCallback` typed arguments as `any[]` by default:\n\n```ts\nfunction useCallback\u003cT extends (...args: any[]) =\u003e any\u003e(\n  callback: T,\n  deps: DependencyList\n): T;\n```\n\nIn React \u003e= 18, the function signature of `useCallback` changed to the following:\n\n```ts\nfunction useCallback\u003cT extends Function\u003e(callback: T, deps: DependencyList): T;\n```\n\nTherefore, the following code will yield \"`Parameter 'e' implicitly has an 'any' type.`\" error in React \u003e= 18, but not \u003c17.\n\n```ts\n// @ts-expect-error Parameter 'e' implicitly has 'any' type.\nuseCallback((e) =\u003e {}, []);\n// Explicit 'any' type.\nuseCallback((e: any) =\u003e {}, []);\n```\n\n#### useReducer\n\nYou can use [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions) for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.\n\n```tsx\nimport { useReducer } from \"react\";\n\nconst initialState = { count: 0 };\n\ntype ACTIONTYPE =\n  | { type: \"increment\"; payload: number }\n  | { type: \"decrement\"; payload: string };\n\nfunction reducer(state: typeof initialState, action: ACTIONTYPE) {\n  switch (action.type) {\n    case \"increment\":\n      return { count: state.count + action.payload };\n    case \"decrement\":\n      return { count: state.count - Number(action.payload) };\n    default:\n      throw new Error();\n  }\n}\n\nfunction Counter() {\n  const [state, dispatch] = useReducer(reducer, initialState);\n  return (\n    \u003c\u003e\n      Count: {state.count}\n      \u003cbutton onClick={() =\u003e dispatch({ type: \"decrement\", payload: \"5\" })}\u003e\n        -\n      \u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch({ type: \"increment\", payload: 5 })}\u003e\n        +\n      \u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6WfTDRSvKnMgpEIgBhxTIJwEQANZSWRjI5SdPIF1u8RXMayZ7lSphEnRWLxbFNagAVmomhF6fZqYA9OXKxxM2KQWWK1WoTW643m63pB2u+7e-3SkEQsPamOGik1FO55p08jl6vdxuKcvv8h4yAmhAA)\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003eUsage with \u003ccode\u003eReducer\u003c/code\u003e from \u003ccode\u003eredux\u003c/code\u003e\u003c/b\u003e\u003c/summary\u003e\n\nIn case you use the [redux](https://github.com/reduxjs/redux) library to write reducer function, It provides a convenient helper of the format `Reducer\u003cState, Action\u003e` which takes care of the return type for you.\n\nSo the above reducer example becomes:\n\n```tsx\nimport { Reducer } from 'redux';\n\nexport function reducer: Reducer\u003cAppState, Action\u003e() {}\n```\n\n\u003c/details\u003e\n\n#### useEffect / useLayoutEffect\n\nBoth of `useEffect` and `useLayoutEffect` are used for performing \u003cb\u003eside effects\u003c/b\u003e and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When using `useEffect`, take care not to return anything other than a function or `undefined`, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:\n\n```ts\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(\n    () =\u003e\n      setTimeout(() =\u003e {\n        /* do stuff */\n      }, timerMs),\n    [timerMs]\n  );\n  // bad example! setTimeout implicitly returns a number\n  // because the arrow function body isn't wrapped in curly braces\n  return null;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eSolution to the above example\u003c/b\u003e\u003c/summary\u003e\n\n```tsx\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(() =\u003e {\n    setTimeout(() =\u003e {\n      /* do stuff */\n    }, timerMs);\n  }, [timerMs]);\n  // better; use the void keyword to make sure you return undefined\n  return null;\n}\n```\n\n\u003c/details\u003e\n\n#### useRef\n\nIn TypeScript, `useRef` returns a reference that is either [read-only](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1025-L1039) or [mutable](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1012-L1023), depends on whether your type argument fully covers the initial value or not. Choose one that suits your use case.\n\n##### Option 1: DOM element ref\n\n**[To access a DOM element](https://reactjs.org/docs/refs-and-the-dom.html):** provide only the element type as argument, and use `null` as initial value. In this case, the returned reference will have a read-only `.current` that is managed by React. TypeScript expects you to give this ref to an element's `ref` prop:\n\n```tsx\nfunction Foo() {\n  // - If possible, prefer as specific as possible. For example, HTMLDivElement\n  //   is better than HTMLElement and way better than Element.\n  // - Technical-wise, this returns RefObject\u003cHTMLDivElement\u003e\n  const divRef = useRef\u003cHTMLDivElement\u003e(null);\n\n  useEffect(() =\u003e {\n    // Note that ref.current may be null. This is expected, because you may\n    // conditionally render the ref-ed element, or you may forget to assign it\n    if (!divRef.current) throw Error(\"divRef is not assigned\");\n\n    // Now divRef.current is sure to be HTMLDivElement\n    doSomethingWith(divRef.current);\n  });\n\n  // Give the ref to an element so React can manage it for you\n  return \u003cdiv ref={divRef}\u003eetc\u003c/div\u003e;\n}\n```\n\nIf you are sure that `divRef.current` will never be null, it is also possible to use the non-null assertion operator `!`:\n\n```tsx\nconst divRef = useRef\u003cHTMLDivElement\u003e(null!);\n// Later... No need to check if it is null\ndoSomethingWith(divRef.current);\n```\n\nNote that you are opting out of type safety here - you will have a runtime error if you forget to assign the ref to an element in the render, or if the ref-ed element is conditionally rendered.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eTip: Choosing which \u003ccode\u003eHTMLElement\u003c/code\u003e to use\u003c/b\u003e\u003c/summary\u003e\n  \nRefs demand specificity - it is not enough to just specify any old `HTMLElement`. If you don't know the name of the element type you need, you can check [lib.dom.ts](https://github.com/microsoft/TypeScript/blob/v3.9.5/lib/lib.dom.d.ts#L19224-L19343) or make an intentional type error and let the language service tell you:\n\n![image](https://user-images.githubusercontent.com/6764957/116914284-1c436380-ac7d-11eb-9150-f52c571c5f07.png)\n\n\u003c/details\u003e\n\n##### Option 2: Mutable value ref\n\n**[To have a mutable value](https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables):** provide the type you want, and make sure the initial value fully belongs to that type:\n\n```tsx\nfunction Foo() {\n  // Technical-wise, this returns MutableRefObject\u003cnumber | null\u003e\n  const intervalRef = useRef\u003cnumber | null\u003e(null);\n\n  // You manage the ref yourself (that's why it's called MutableRefObject!)\n  useEffect(() =\u003e {\n    intervalRef.current = setInterval(...);\n    return () =\u003e clearInterval(intervalRef.current);\n  }, []);\n\n  // The ref is not passed to any element's \"ref\" prop\n  return \u003cbutton onClick={/* clearInterval the ref */}\u003eCancel timer\u003c/button\u003e;\n}\n```\n\n##### See also\n\n- [Related issue by @rajivpunjabi](https://github.com/typescript-cheatsheets/react/issues/388) - [Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwCwAUI7hAHarwCCYYcAvHAAUASn4A+OAG9GjOHAD0CBLLnKGcxHABiwKBzgQwMYGxS4WUACbBWAczgwIcSxFwBXEFlYxkxtgDoVTQBJVmBjZAAbOAA3KLcsOAB3YEjogCNE1jc0-zgAGQBPG3tHOAAVQrAsAGVcKGAjOHTCuDdUErhWNgBabLSUVFQsWBNWA2qoX2hA9VU4AGFKXyx0AFk3H3TIxOwCOAB5dIArLHwgpHcoSm84MGJJmFbgdG74ZcsDVkjC2Y01f7yFQsdjvLAEACM-EwVBg-naWD2AB4ABLlNb5GpgZCsACiO083jEgn6kQAhMJ6HMQfpKJCFpE2IkBNg8HCEci0RisTj8VhCTBiaSKVSVIoAaoLnBQuFgFFYvFEikBpkujkMps4FgAB7VfCdLmY7F4gleOFwAByEHg7U63VYfXVg2Go1MhhG0ygf3mAHVUtF6jgYLtwUdTvguta4Bstjs9mGznCpVcbvB7u7YM90B8vj9vYgLkDqWxaeCAEzQ1n4eHDTnoo2801EknqykyObii5SmpnNifA5GMZmCzWOwOJwudwC3xjKUyiLROKRBLJf3NLJO9KanV64xj0koVifQ08k38s1Sv0DJZBxIx5DbRGhk6J5Nua5mu4PEZPOAvSNgsgnxsHmXZzIgRZyDSYIEAAzJWsI1k+BCovWp58gKcAAD5qmkQqtqKHbyCexoYRecw7IQugcAs76ptCdIQv4KZmoRcjyMRaGkU28A4aSKiUXAwwgpYtEfrcAh0mWzF0ax7bsZx3Lceetx8eqAlYPAMAABa6KJskSXAdKwTJ4kwGxCjyKy-bfK05SrDA8mWVagHAbZeScOY0CjqUE6uOgqDaRAOSfKqOYgb8KiMaZ9GSeCEIMkyMVyUwRHWYc7nSvAgUQEk6AjMQXpReWyWGdFLHeBZHEuTCQEZT8xVwaV8BxZCzUWZQMDvuMghBHASJVnCWhTLYApiH1chIqgxpGeCfCSIxAC+Yj3o+8YvvgSLyNNOLjeBGhTTNdLzVJy3reGMBbTtrB7RoB3XbNBAneCsHLatcbPhdV3GrdB1WYhw3IKNZq-W2DCLYRO7QPAljgsgORcDwVJAA)\n- [Example from Stefan Baumgartner](https://fettblog.eu/typescript-react/hooks/#useref) - [Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wFgAoCzAVwDsNgJa4AVJADxgElaxqYA6sBgALAGIQ01AM4AhfjCYAKAJRwA3hThwA9DrjBaw4CgA2waUjgB3YSLi1qp0wBo4AI35wYSZ6wCeYEgAymhQwGDw1lYoRHCmEBAA1oYA5nCY0HAozAASLACyADI8fDAAoqZIIEi0MFpwaEzS8IZllXAAvIjEMAB0MkjImAA8+cWl-JXVtTAAfEqOzioA3A1NtC1wTPIwirQAwuZoSV1wql1zGg3aenAt4RgOTqaNIkgn0g5ISAAmcDJvBA3h9TsBMAZeFNXjl-lIoEQ6nAOBZ+jddPpPPAmGgrPDEfAUS1pG5hAYvhAITBAlZxiUoRUqjU6m5RIDhOi7iIUF9RFYaqIIP9MlJpABCOCAUHJ0eDzm1oXAAGSKyHtUx9fGzNSacjaPWq6Ea6gI2Z9EUyVRrXV6gC+DRtVu0RBgxuYSnRIzm6O06h0ACpIdlfr9jExSQyOkxTP5GjkPFZBv9bKIDYSmbNpH04ABNFD+CV+nR2636kby+BETCddTlyo27w0zr4HycfC6L0lvUjLH7baHY5Jas7BRMI7AE42uYSUXed6pkY6HtMDulnQruCrCg2oA)\n\n#### useImperativeHandle\n\nBased on this [Stackoverflow answer](https://stackoverflow.com/a/69292925/5415299):\n\n```tsx\n// Countdown.tsx\n\n// Define the handle types which will be passed to the forwardRef\nexport type CountdownHandle = {\n  start: () =\u003e void;\n};\n\ntype CountdownProps = {};\n\nconst Countdown = forwardRef\u003cCountdownHandle, CountdownProps\u003e((props, ref) =\u003e {\n  useImperativeHandle(ref, () =\u003e ({\n    // start() has type inference here\n    start() {\n      alert(\"Start\");\n    },\n  }));\n\n  return \u003cdiv\u003eCountdown\u003c/div\u003e;\n});\n```\n\n```tsx\n// The component uses the Countdown component\n\nimport Countdown, { CountdownHandle } from \"./Countdown.tsx\";\n\nfunction App() {\n  const countdownEl = useRef\u003cCountdownHandle\u003e(null);\n\n  useEffect(() =\u003e {\n    if (countdownEl.current) {\n      // start() has type inference here as well\n      countdownEl.current.start();\n    }\n  }, []);\n\n  return \u003cCountdown ref={countdownEl} /\u003e;\n}\n```\n\n##### See also:\n\n- [Using ForwardRefRenderFunction](https://stackoverflow.com/a/62258685/5415299)\n\n#### Custom Hooks\n\nIf you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScript will infer a union type (when you actually want different types in each position of the array). Instead, use [TS 3.4 const assertions](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions):\n\n```tsx\nimport { useState } from \"react\";\n\nexport function useLoading() {\n  const [isLoading, setState] = useState(false);\n  const load = (aPromise: Promise\u003cany\u003e) =\u003e {\n    setState(true);\n    return aPromise.finally(() =\u003e setState(false));\n  };\n  return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?target=5\u0026jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCpAD0ljkwFcA7DYCZuRgZyQBkIKACbBmAcwAUASjgBvCnDhoO3eAG1g3AcNFiANHF4wAyjBQwkAXTgBeRMRgA6HklPmkEzCgA2vKQG4FJRV4b0EhWzgJFAAFHBBNJAAuODjcRIAeFGYATwA+GRs8uSDFIzcLCRgoRiQA0rgiGEYoTlj4xMdMUR9vHIlpW2Lys0qvXzr68kUAX0DpxqRm1rgNLXDdAzDhaxRuYOZVfzgAehO4UUwkKH21ACMICG9UZgMYHLAkCEw4baFrUSqVARb5RB5PF5wAA+cHen1BfykaksFBmQA)\n\nThis way, when you destructure you actually get the right types based on destructure position.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eAlternative: Asserting a tuple return type\u003c/b\u003e\u003c/summary\u003e\n\nIf you are [having trouble with const assertions](https://github.com/babel/babel/issues/9800), you can also assert or define the function return types:\n\n```tsx\nimport { useState } from \"react\";\n\nexport function useLoading() {\n  const [isLoading, setState] = useState(false);\n  const load = (aPromise: Promise\u003cany\u003e) =\u003e {\n    setState(true);\n    return aPromise.finally(() =\u003e setState(false));\n  };\n  return [isLoading, load] as [\n    boolean,\n    (aPromise: Promise\u003cany\u003e) =\u003e Promise\u003cany\u003e\n  ];\n}\n```\n\nA helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:\n\n```tsx\nfunction tuplify\u003cT extends any[]\u003e(...elements: T) {\n  return elements;\n}\n\nfunction useArray() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() =\u003e {}).current;\n  return [numberValue, functionValue]; // type is (number | (() =\u003e void))[]\n}\n\nfunction useTuple() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() =\u003e {}).current;\n  return tuplify(numberValue, functionValue); // type is [number, () =\u003e void]\n}\n```\n\n\u003c/details\u003e\n\nNote that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however.\n\n#### More Hooks + TypeScript reading:\n\n- https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d\n- https://fettblog.eu/typescript-react/hooks/#useref\n\nIf you are writing a React Hooks library, don't forget that you should also expose your types for users to use.\n\n#### Example React Hooks + TypeScript Libraries:\n\n- https://github.com/mweststrate/use-st8\n- https://github.com/palmerhq/the-platform\n- https://github.com/sw-yx/hooks\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n\u003c!--END-SECTION:hooks--\u003e\n\n\u003c!--START-SECTION:class-components--\u003e\n\n#### Class Components\n\nWithin TypeScript, `React.Component` is a generic type (aka `React.Component\u003cPropType, StateType\u003e`), so you want to provide it with (optional) prop and state type parameters:\n\n```tsx\ntype MyProps = {\n  // using `interface` is also ok\n  message: string;\n};\ntype MyState = {\n  count: number; // like this\n};\nclass App extends React.Component\u003cMyProps, MyState\u003e {\n  state: MyState = {\n    // optional second annotation for better type inference\n    count: 0,\n  };\n  render() {\n    return (\n      \u003cdiv\u003e\n        {this.props.message} {this.state.count}\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgFlqAFHMAZzgF44BvCuHAD0QuAFd2wAHYBzOAANpMJFEzok8uME4oANuwhwIAawFwQSduxQykALjjsYUaTIDcFAL4fyNOo2oAZRgUZW4+MzQIMSkYBykxEAAjFTdhUV1gY3oYAAttLx80XRQrOABBMDA4JAAPZSkAE05kdBgAOgBhXEgpJFiAHiZWCA4AGgDg0KQAPgjyQSdphyYpsJ5+BcF0ozAYYAgpPUckKKa4FCkpCBD9w7hMaDgUmGUoOD96aUwVfrQkMyCKIxOJwAAMZm8ZiITRUAAoAJTzbZwIgwMRQKRwOGA7YDRrAABuM1xKN4eW07TAbHY7QsVhsSE8fAptKWynawNinlJcAGQgJxNxCJ8gh55E8QA)\n\nDon't forget that you can export/import/extend these types/interfaces for reuse.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eWhy annotate \u003ccode\u003estate\u003c/code\u003e twice?\u003c/b\u003e\u003c/summary\u003e\n\nIt isn't strictly necessary to annotate the `state` class property, but it allows better type inference when accessing `this.state` and also initializing the state.\n\nThis is because they work in two different ways, the 2nd generic type parameter will allow `this.setState()` to work correctly, because that method comes from the base class, but initializing `state` inside the component overrides the base implementation so you have to make sure that you tell the compiler that you're not actually doing anything different.\n\n[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57).\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cb\u003eNo need for \u003ccode\u003ereadonly\u003c/code\u003e\u003c/b\u003e\u003c/summary\u003e\n\nYou often see sample code include `readonly` to mark props and state immutable:\n\n```tsx\ntype MyProps = {\n  readonly message: string;\n};\ntype MyState = {\n  readonly count: number;\n};\n```\n\nThis is not necessary as `React.Component\u003cP,S\u003e` already marks them as immutable. ([See PR and discussion!](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813))\n\n\u003c/details\u003e\n\n**Class Methods**: Do it like normal, but just remember any arguments for your functions also need to be typed:\n\n```tsx\nclass App extends React.Component\u003c{ message: string }, { count: number }\u003e {\n  state = { count: 0 };\n  render() {\n    return (\n      \u003cdiv onClick={() =\u003e this.increment(1)}\u003e\n        {this.props.message} {this.state.count}\n      \u003c/div\u003e\n    );\n  }\n  increment = (amt: number) =\u003e {\n    // like this\n    this.setState((state) =\u003e ({\n      count: state.count + amt,\n    }));\n  };\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN5wQSBigDmSAFxw6MKMB5q4AXwA0cRWggBXHjG09rIAEZIoJgHwWKcHTBTccAC8FnBWtvZwAAwmANw+cET8bgAUAJTe5L6+RDDWUDxwKQnZcLJ8wABucBA8YtTAaADWQfLpwV4wABbAdCIGaETKdikAjGnGHiWlFt29ImA4YH3KqhrGsz19ugFIIuF2xtO+sgD0FZVTWdlp8ddH1wNDMsFFKCCRji5uGUFe8tNTqc4A0mkg4HM6NNISI6EgYABlfzcFI7QJ-IoA66lA6RNF7XFwADUcHeMGmxjStwSxjuxiAA)\n\n**Class Properties**: If you need to declare class properties for later use, just declare it like `state`, but without assignment:\n\n```tsx\nclass App extends React.Component\u003c{\n  message: string;\n}\u003e {\n  pointer: number; // like this\n  componentDidMount() {\n    this.pointer = 3;\n  }\n  render() {\n    return (\n      \u003cdiv\u003e\n        {this.props.message} and {this.pointer}\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN4U4cEEgYoA5kgBccOjCjAeGgNwUAvgD44i8sshHuUXTwCuIAEZIoJuAHo-OGpgAGskOBgAC2A6JTg0SQhpHhgAEWA+AFkIVxSACgBKGzjlKJiRBxTvOABeOABmMzs4cziifm9C4ublIhhXKB44PJLlOFk+YAA3S1GxmzK6CpwwJdV1LXM4FH4F6KXKp1aesdk-SZnRgqblY-MgA)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n#### Typing getDerivedStateFromProps\n\nBefore you start using `getDerivedStateFromProps`, please go through the [documentation](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [You Probably Don't Need Derived State](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). Derived State can be implemented using hooks which can also help set up memoization.\n\nHere are a few ways in which you can annotate `getDerivedStateFromProps`\n\n1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it.\n\n```tsx\nclass Comp extends React.Component\u003cProps, State\u003e {\n  static getDerivedStateFromProps(\n    props: Props,\n    state: State\n  ): Partial\u003cState\u003e | null {\n    //\n  }\n}\n```\n\n2. When you want the function's return value to determine your state.\n\n```tsx\nclass Comp extends React.Component\u003c\n  Props,\n  ReturnType\u003ctypeof Comp[\"getDerivedStateFromProps\"]\u003e\n\u003e {\n  static getDerivedStateFromProps(props: Props) {}\n}\n```\n\n3. When you want derived state with other state fields and memoization\n\n```tsx\ntype CustomValue = any;\ninterface Props {\n  propA: CustomValue;\n}\ninterface DefinedState {\n  otherStateField: string;\n}\ntype State = DefinedState \u0026 ReturnType\u003ctypeof transformPropsToState\u003e;\nfunction transformPropsToState(props: Props) {\n  return {\n    savedPropA: props.propA, // save for memoization\n    derivedState: props.propA,\n  };\n}\nclass Comp extends React.PureComponent\u003cProps, State\u003e {\n  constructor(props: Props) {\n    super(props);\n    this.state = {\n      otherStateField: \"123\",\n      ...transformPropsToState(props),\n    };\n  }\n  static getDerivedStateFromProps(props: Props, state: State) {\n    if (isEqual(props.propA, state.savedPropA)) return null;\n    return transformPropsToState(props);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOYAZwFEBHAVxQBs5tcD2IATFHQAWAOnpJWHMuQowAnmCRwAwizoxcANQ4tlAXjgoAdvIDcFYMZhIomdMoAKOMHTgBvCnDhgXAQQAuVXVNEB12PQtyAF9La1t7NGUAESRMKyR+AGUYFBsPLzgIGGFbHLykADFgJHZ+II0oKwBzKNjyBSU4cvzDVPTjTJ7lADJEJBgWKGMAFUUkAB5OpAhMOBgoEzpMaBBnCFcZiGGAPijMFmMMYAhjdc3jbd39w+PcmwAKXwO6IJe6ACUBXI3iIk2mwO83joKAAbpkXoEfC46KJvmA-AAaOAAehxcBh8K40DgICQIAgwAAXnkbsZCt5+LZgPDsu8kEF0aj0X5CtE2hQ0OwhG4VLgwHAkAAPGzGfhuZDoGCiRxTJBi8C3JDWBb-bGnSFwNC3RosDDQL4ov4ooGeEFQugsJRQS0-AFRKHrYT0UQaCpwQx2z3eYqlKDDaq1epwABEAEYAEwAZhjmIZUNEmY2Wx2UD2KKOw1drgB6f5fMKfpgwDQcGaE1STVZEZw+Z+xd+cD1BPZQWGtvTwDWH3ozDY7A7aP82KrSF9cIR-gBQLBUzuxhY7HYHqhq4h2ceubbryLXPdFZiQA)\n\n\u003c!--END-SECTION:class-components--\u003e\n\n\u003c!--START-SECTION:default-props--\u003e\n\n#### You May Not Need `defaultProps`\n\nAs per [this tweet](https://twitter.com/dan_abramov/status/1133878326358171650), defaultProps will eventually be deprecated. You can check the discussions here:\n\n- [Original tweet](https://twitter.com/hswolff/status/1133759319571345408)\n- More info can also be found in [this article](https://medium.com/@matanbobi/react-defaultprops-is-dying-whos-the-contender-443c19d9e7f1)\n\nThe consensus is to use object default values.\n\nFunction Components:\n\n```tsx\ntype GreetProps = { age?: number };\n\nconst Greet = ({ age = 21 }: GreetProps) =\u003e // etc\n```\n\nClass Components:\n\n```tsx\ntype GreetProps = {\n  age?: number;\n};\n\nclass Greet extends React.Component\u003cGreetProps\u003e {\n  render() {\n    const { age = 21 } = this.props;\n    /*...*/\n  }\n}\n\nlet el = \u003cGreet age={3} /\u003e;\n```\n\n#### Typing `defaultProps`\n\nType inference improved greatly for `defaultProps` in [TypeScript 3.0+](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html), although [some edge cases are still problematic](https://github.com/typescript-cheatsheets/react/issues/61).\n\n**Function Components**\n\n```tsx\n// using typeof as a shortcut; note that it hoists!\n// you can also declare the type of DefaultProps if you choose\n// e.g. https://github.com/typescript-cheatsheets/react/issues/415#issuecomment-841223219\ntype GreetProps = { age: number } \u0026 typeof defaultProps;\n\nconst defaultProps = {\n  age: 21,\n};\n\nconst Greet = (props: GreetProps) =\u003e {\n  // etc\n};\nGreet.defaultProps = defaultProps;\n```\n\n_[See this in TS Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAOKVYwAKxY6ALxwA3igDmWAFxwAdgFcQAIyxQ4AXzgAyOM1YQCcACZYCyeQBte-VPVwRZqeCbOXrEAXGEi6cCdLgAJgBGABo6dXo6e0d4TixuLzgACjAbGXjuPg9UAEovAD5RXzhKGHkoWTgAHiNgADcCkTScgDpkSTgAeiQFZVVELvVqrrrGiPpMmFaXcytsz2FZtwXbOiA)_\n\nFor **Class components**, there are [a couple ways to do it](https://github.com/typescript-cheatsheets/react/pull/103#issuecomment-481061483) (including using the `Pick` utility type) but the recommendation is to \"reverse\" the props definition:\n\n```tsx\ntype GreetProps = typeof Greet.defaultProps \u0026 {\n  age: number;\n};\n\nclass Greet extends React.Component\u003cGreetProps\u003e {\n  static defaultProps = {\n    age: 21,\n  };\n  /*...*/\n}\n\n// Type-checks! No type assertions needed!\nlet el = \u003cGreet age={3} /\u003e;\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003e\u003ccode\u003eReact.JSX.LibraryManagedAttributes\u003c/code\u003e nuance for library authors\u003c/b\u003e\u003c/summary\u003e\n\nThe above implementations work fine for App creators, but sometimes you want to be able to export `GreetProps` so that others can consume it. The problem here is that the way `GreetProps` is defined, `age` is a required prop when it isn't because of `defaultProps`.\n\nThe insight to have here is that [`GreetProps` is the _internal_ contract for your component, not the _external_, consumer facing contract](https://github.com/typescript-cheatsheets/react/issues/66#issuecomment-453878710). You could create a separate type specifically for export, or you could make use of the `React.JSX.LibraryManagedAttributes` utility:\n\n```tsx\n// internal contract, should not be exported out\ntype GreetProps = {\n  age: number;\n};\n\nclass Greet extends Component\u003cGreetProps\u003e {\n  static defaultProps = { age: 21 };\n}\n\n// external contract\nexport type ApparentGreetProps = React.JSX.LibraryManagedAttributes\u003c\n  typeof Greet,\n  GreetProps\n\u003e;\n```\n\nThis will work properly, although hovering over`ApparentGreetProps`may be a little intimidating. You can reduce this boilerplate with the`ComponentProps` utility detailed below.\n\n\u003c/details\u003e\n\n#### Consuming Props of a Component with defaultProps\n\nA component with `defaultProps` may seem to have some required props that actually aren't.\n\n##### Problem Statement\n\nHere's what you want to do:\n\n```tsx\ninterface IProps {\n  name: string;\n}\nconst defaultProps = {\n  age: 25,\n};\nconst GreetComponent = ({ name, age }: IProps \u0026 typeof defaultProps) =\u003e (\n  \u003cdiv\u003e{`Hello, my name is ${name}, ${age}`}\u003c/div\u003e\n);\nGreetComponent.defaultProps = defaultProps;\n\nconst TestComponent = (props: React.ComponentProps\u003ctypeof GreetComponent\u003e) =\u003e {\n  return \u003ch1 /\u003e;\n};\n\n// Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'\nconst el = \u003cTestComponent name=\"foo\" /\u003e;\n```\n\n##### Solution\n\nDefine a utility that applies `React.JSX.LibraryManagedAttributes`:\n\n```tsx\ntype ComponentProps\u003cT\u003e = T extends\n  | React.ComponentType\u003cinfer P\u003e\n  | React.Component\u003cinfer P\u003e\n  ? React.JSX.LibraryManagedAttributes\u003cT, P\u003e\n  : never;\n\nconst TestComponent = (props: ComponentProps\u003ctypeof GreetComponent\u003e) =\u003e {\n  return \u003ch1 /\u003e;\n};\n\n// No error\nconst el = \u003cTestComponent name=\"foo\" /\u003e;\n```\n\n[_See this in TS Playground_](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAMImQB2W3MABWJhUAHgAqAPjgBeOOLhYAHjD4ATdNjwwAdJ3ARe-cSyyjg3AlihwB0gD6Yqu-Tz4xzl67cl04cAH44ACkAZQANHQAZYAAjKGQoJgBZZG5kAHMsNQBBGBgoOIBXVTFxABofPzgALjheADdrejoLVSgCPDYASSEIETgAb2r0kCw61AKLDPoAXzpcQ0m4NSxOooAbQWF0OWH-TPG4ACYAVnK6WfpF7mWAcUosGFdDd1k4AApB+uQxysO4LM6r0dnAAGRwZisCAEFZrZCbbb9VAASlk0g+1VEamADUkgwABgAJLAbDYQSogJg-MZwYDoAAkg1GWFmlSZh1mBNmogA9Di8XQUfQHlgni8jLpVustn0BnJpQjZTsWrzeXANsh2gwbstxFhJhK3nIPmAdnUjfw5WIoVgYXBReKuK9+JI0TJpPs4JQYEUoNw4KIABYARjgvN8VwYargADkIIooMQoAslvBSe8JAbns7JTSsDIyAQIBAyOHJDQgA)\n\n#### Misc Discussions and Knowledge\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eWhy does \u003ccode\u003eReact.FC\u003c/code\u003e break \u003ccode\u003edefaultProps\u003c/code\u003e?\u003c/b\u003e\u003c/summary\u003e\n\nYou can check the discussions here:\n\n- https://medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680\n- https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30695\n- https://github.com/typescript-cheatsheets/react/issues/87\n\nThis is just the current state and may be fixed in future.\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eTypeScript 2.9 and earlier\u003c/b\u003e\u003c/summary\u003e\n\nFor TypeScript 2.9 and earlier, there's more than one way to do it, but this is the best advice we've yet seen:\n\n```ts\ntype Props = Required\u003ctypeof MyComponent.defaultProps\u003e \u0026 {\n  /* additional props here */\n};\n\nexport class MyComponent extends React.Component\u003cProps\u003e {\n  static defaultProps = {\n    foo: \"foo\",\n  };\n}\n```\n\nOur former recommendation used the `Partial type` feature in TypeScript, which means that the current interface will fulfill a partial version on the wrapped interface. In that way we can extend defaultProps without any changes in the types!\n\n```ts\ninterface IMyComponentProps {\n  firstProp?: string;\n  secondProp: IPerson[];\n}\n\nexport class MyComponent extends React.Component\u003cIMyComponentProps\u003e {\n  public static defaultProps: Partial\u003cIMyComponentProps\u003e = {\n    firstProp: \"default\",\n  };\n}\n```\n\nThe problem with this approach is it causes complex issues with the type inference working with `React.JSX.LibraryManagedAttributes`. Basically it causes the compiler to think that when creating a JSX expression with that component, that all of its props are optional.\n\n[See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react/issues/57) and [here](https://github.com/typescript-cheatsheets/react/issues/61).\n\n\u003c/details\u003e\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n\u003c!--END-SECTION:default-props--\u003e\n\n\u003c!--START-SECTION:basic-type-examples--\u003e\n\n#### Typing Component Props\n\nThis is intended as a basic orientation and reference for React developers familiarizing with TypeScript.\n\n#### Basic Prop Types Examples\n\nA list of TypeScript types you will likely use in a React+TypeScript app:\n\n```tsx\ntype AppProps = {\n  message: string;\n  count: number;\n  disabled: boolean;\n  /** array of a type! */\n  names: string[];\n  /** string literals to specify exact string values, with a union type to join them together */\n  status: \"waiting\" | \"success\";\n  /** an object with known properties (but could have more at runtime) */\n  obj: {\n    id: string;\n    title: string;\n  };\n  /** array of objects! (common) */\n  objArr: {\n    id: string;\n    title: string;\n  }[];\n  /** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */\n  obj2: object;\n  /** an interface with no required properties - (NOT COMMON, except for things like `React.Component\u003c{}, State\u003e`) */\n  obj3: {};\n  /** a dict object with any number of properties of the same type */\n  dict1: {\n    [key: string]: MyTypeHere;\n  };\n  dict2: Record\u003cstring, MyTypeHere\u003e; // equivalent to dict1\n  /** function that doesn't take or return anything (VERY COMMON) */\n  onClick: () =\u003e void;\n  /** function with named prop (VERY COMMON) */\n  onChange: (id: number) =\u003e void;\n  /** function type syntax that takes an event (VERY COMMON) */\n  onChange: (event: React.ChangeEvent\u003cHTMLInputElement\u003e) =\u003e void;\n  /** alternative function type syntax that takes an event (VERY COMMON) */\n  onClick(event: React.MouseEvent\u003cHTMLButtonElement\u003e): void;\n  /** any function as long as you don't invoke it (not recommended) */\n  onSomething: Function;\n  /** an optional prop (VERY COMMON!) */\n  optional?: OptionalType;\n  /** when passing down the state setter function returned by `useState` to a child component. `number` is an example, swap out with whatever the type of your state */\n  setState: React.Dispatch\u003cReact.SetStateAction\u003cnumber\u003e\u003e;\n};\n```\n\n##### `object` as the non-primitive type\n\n`object` is a common source of misunderstanding in TypeScript. It does not mean \"any object\" but rather \"any non-primitive type\", which means it represents anything that is not `number`, `bigint`, `string`, `boolean`, `symbol`, `null` or `undefined`.\n\nTyping \"any non-primitive value\" is most likely not something that you should do much in React, which means you will probably not use `object` much.\n\n##### Empty interface, `{}` and `Object`\n\nAn empty interface, `{}` and `Object` all represent \"any non-nullish value\"—not \"an empty object\" as you might think. [Using these types is a common source of misunderstanding and is not recommended](https://typescript-eslint.io/rules/no-empty-interface/).\n\n```ts\ninterface AnyNonNullishValue {} // equivalent to `type AnyNonNullishValue = {}` or `type AnyNonNullishValue = Object`\n\nlet value: AnyNonNullishValue;\n\n// these are all fine, but might not be expected\nvalue = 1;\nvalue = \"foo\";\nvalue = () =\u003e alert(\"foo\");\nvalue = {};\nvalue = { foo: \"bar\" };\n\n// these are errors\nvalue = undefined;\nvalue = null;\n```\n\n#### Useful React Prop Type Examples\n\nRelevant for components that accept other React components as props.\n\n```tsx\nexport declare interface AppProps {\n  children?: React.ReactNode; // best, accepts everything React can render\n  childrenElement: React.JSX.Element; // A single React element\n  style?: React.CSSProperties; // to pass through style props\n  onChange?: React.FormEventHandler\u003cHTMLInputElement\u003e; // form events! the generic parameter is the type of event.target\n  //  more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring\n  props: Props \u0026 React.ComponentPropsWithoutRef\u003c\"button\"\u003e; // to impersonate all the props of a button element and explicitly not forwarding its ref\n  props2: Props \u0026 React.ComponentPropsWithRef\u003cMyButtonWithForwardRef\u003e; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eSmall \u003ccode\u003eReact.ReactNode\u003c/code\u003e edge case before React 18\u003c/b\u003e\u003c/summary\u003e\n\nBefore the [React 18 type updates](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210), this code typechecked but had a runtime error:\n\n```tsx\ntype Props = {\n  children?: React.ReactNode;\n};\n\nfunction Comp({ children }: Props) {\n  return \u003cdiv\u003e{children}\u003c/div\u003e;\n}\nfunction App() {\n  // Before React 18: Runtime error \"Objects are not valid as a React child\"\n  // After React 18: Typecheck error \"Type '{}' is not assignable to type 'ReactNode'\"\n  return \u003cComp\u003e{{}}\u003c/Comp\u003e;\n}\n```\n\nThis is because `ReactNode` includes `ReactFragment` which allowed type `{}` before React 18.\n\n[Thanks @pomle for raising this.](https://github.com/typescript-cheatsheets/react/issues/357)\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n \u003csummary\u003e\u003cb\u003eReact.JSX.Element vs React.ReactNode?\u003c/b\u003e\u003c/summary\u003e\n\nQuote [@ferdaber](https://github.com/typescript-cheatsheets/react/issues/57): A more technical explanation is that a valid React node is not the same thing as what is returned by `React.createElement`. Regardless of what a component ends up rendering, `React.createElement` always returns an object, which is the `React.JSX.Element` interface, but `React.ReactNode` is the set of all possible return values of a component.\n\n- `React.JSX.Element` -\u003e Return value of `React.createElement`\n- `React.ReactNode` -\u003e Return value of a component\n\n\u003c/details\u003e\n\n[More discussion: Where ReactNode does not overlap with React.JSX.Element](https://github.com/typescript-cheatsheets/react/issues/129)\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n#### Types or Interfaces?\n\nYou can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use?\n\n##### TL;DR\n\nUse Interface until You Need Type - [orta](https://twitter.com/orta/status/1356129195835973632?s=20).\n\n##### More Advice\n\nHere's a helpful rule of thumb:\n\n- always use `interface` for public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via _declaration merging_ if some definitions are missing.\n\n- consider using `type` for your React Component Props and State, for consistency and because it is more constrained.\n\nYou can read more about the reasoning behind this rule of thumb in [Interface vs Type alias in TypeScript 2.7](https://medium.com/@martin_hotell/interface-vs-type-alias-in-typescript-2-7-2a8f1777af4c).\n\nThe TypeScript Handbook now also includes guidance on [Differences Between Type Aliases and Interfaces](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces).\n\n\u003e Note: At scale, there are performance reasons to prefer interfaces ([see official Microsoft notes on this](https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections)) but [take this with a grain of salt](https://news.ycombinator.com/item?id=25201887)\n\nTypes are useful for union types (e.g. `type MyType = TypeA | TypeB`) whereas Interfaces are better for declaring dictionary shapes and then `implementing` or `extending` them.\n\n##### Useful table for Types vs Interfaces\n\nIt's a nuanced topic, don't get too hung up on it. Here's a handy table:\n\n| Aspect                                          | Type | Interface |\n| ----------------------------------------------- | :--: | :-------: |\n| Can describe functions                          |  ✅  |    ✅     |\n| Can describe constructors                       |  ✅  |    ✅     |\n| Can describe tuples                             |  ✅  |    ✅     |\n| Interfaces can extend it                        |  ⚠️  |    ✅     |\n| Classes can extend it                           |  🚫  |    ✅     |\n| Classes can implement it (`implements`)         |  ⚠️  |    ✅     |\n| Can intersect another one of its kind           |  ✅  |    ⚠️     |\n| Can create a union with another one of its kind |  ✅  |    🚫     |\n| Can be used to create mapped types              |  ✅  |    🚫     |\n| Can be mapped over with mapped types            |  ✅  |    ✅     |\n| Expands in error messages and logs              |  ✅  |    🚫     |\n| Can be augmented                                |  🚫  |    ✅     |\n| Can be recursive                                |  ⚠️  |    ✅     |\n\n⚠️ In some cases\n\n(source: [Karol Majewski](https://twitter.com/karoljmajewski/status/1082413696075382785))\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n\u003c!--END-SECTION:basic-type-examples--\u003e\n\n\u003c!--START-SECTION:get-derived-state-from-props--\u003e\n\n## getDerivedStateFromProps\n\nBefore you start using `getDerivedStateFromProps`, please go through the [documentation](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [You Probably Don't Need Derived State](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). Derived State can be easily achieved using hooks which can also help set up memoization easily.\n\nHere are a few ways in which you can annotate `getDerivedStateFromProps`\n\n1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it.\n\n```tsx\nclass Comp extends React.Component\u003cProps, State\u003e {\n  static getDerivedStateFromProps(\n    props: Props,\n    state: State\n  ): Partial\u003cState\u003e | null {\n    //\n  }\n}\n```\n\n2. When you want the function's return value to determine your state.\n\n```tsx\nclass Comp extends React.Component\u003c\n  Props,\n  ReturnType\u003ctypeof Comp[\"getDerivedStateFromProps\"]\u003e\n\u003e {\n  static getDerivedStateFromProps(props: Props) {}\n}\n```\n\n3. When you want derived state with other state fields and memoization\n\n```tsx\ntype CustomValue = any;\ninterface Props {\n  propA: CustomValue;\n}\ninterface DefinedState {\n  otherStateField: string;\n}\ntype State = DefinedState \u0026 ReturnType\u003ctypeof transformPropsToState\u003e;\nfunction transformPropsToState(props: Props) {\n  return {\n    savedPropA: props.propA, // save for memoization\n    derivedState: props.propA,\n  };\n}\nclass Comp extends React.PureComponent\u003cProps, State\u003e {\n  constructor(props: Props) {\n    super(props);\n    this.state = {\n      otherStateField: \"123\",\n      ...transformPropsToState(props),\n    };\n  }\n  static getDerivedStateFromProps(props: Props, state: State) {\n    if (isEqual(props.propA, state.savedPropA)) return null;\n    return transformPropsToState(props);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOYAZwFEBHAVxQBs5tcD2IATFHQAWAOnpJWHMuQowAnmCRwAwizoxcANQ4tlAXjgoAdvIDcFYMZhIomdMoAKOMHTgBvCnDhgXAQQAuVXVNEB12PQtyAF9La1t7NGUAESRMKyR+AGUYFBsPLzgIGGFbHLykADFgJHZ+II0oKwBzKNjyBSU4cvzDVPTjTJ7lADJEJBgWKGMAFUUkAB5OpAhMOBgoEzpMaBBnCFcZiGGAPijMFmMMYAhjdc3jbd39w+PcmwAKXwO6IJe6ACUBXI3iIk2mwO83joKAAbpkXoEfC46KJvmA-AAaOAAehxcBh8K40DgICQIAgwAAXnkbsZCt5+LZgPDsu8kEF0aj0X5CtE2hQ0OwhG4VLgwHAkAAPGzGfhuZDoGCiRxTJBi8C3JDWBb-bGnSFwNC3RosDDQL4ov4ooGeEFQugsJRQS0-AFRKHrYT0UQaCpwQx2z3eYqlKDDaq1epwABEAEYAEwAZhjmIZUNEmY2Wx2UD2KKOw1drgB6f5fMKfpgwDQcGaE1STVZEZw+Z+xd+cD1BPZQWGtvTwDWH3ozDY7A7aP82KrSF9cIR-gBQLBUzuxhY7HYHqhq4h2ceubbryLXPdFZiQA)\n\n\u003c!--END-SECTION:get-derived-state-from-props--\u003e\n\n\u003c!--START-SECTION:forms-and-events--\u003e\n\n#### Forms and Events\n\nIf performance is not an issue (and it usually isn't!), inlining handlers is easiest as you can just use [type inference and contextual typing](https://www.typescriptlang.org/docs/handbook/type-inference.html#contextual-typing):\n\n```tsx\nconst el = (\n  \u003cbutton\n    onClick={(event) =\u003e {\n      /* event will be correctly typed automatically! */\n    }}\n  /\u003e\n);\n```\n\nBut if you need to define your event handler separately, IDE tooling really comes in handy here, as the @type definitions come with a wealth of typing. Type what you are looking for and usually the autocomplete will help you out. Here is what it looks like for an `onChange` for a form event:\n\n```tsx\ntype State = {\n  text: string;\n};\nclass App extends React.Component\u003cProps, State\u003e {\n  state = {\n    text: \"\",\n  };\n\n  // typing on RIGHT hand side of =\n  onChange = (e: React.FormEvent\u003cHTMLInputElement\u003e): void =\u003e {\n    this.setState({ text: e.currentTarget.value });\n  };\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cinput type=\"text\" value={this.state.text} onChange={this.onChange} /\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2KA9Drg8IcMDjB1tcblwBccOjCjAeAcwDcmlRQB8W8ovso3HAAvL6KilYwtgBE0R7ulH5wepYAnmBOznAQPIgAkgDiABIAKnAAFij8dsB8SNmYIZo5YpUu9aEAFEi2QhgiAGLQIACiAG4ysqUAsgAyeTxgAK4wI9RIIDJeAJS2YxC1IT5KFjDlwHQidEgwAMowgUidSpacUewiaEtQRDwwJSgoM4biIxihqEt6iptglFCpYXBfnUoJ1tmFwkQYN9cp0LIpZHxgGMvHjwrInMt4DB0khgtFItE4GCIbSlGcLlcHtwRJEVNkeK0qsDgmzzpcWm1gXydCSkuE4LIdITiRYYR4KCogA)\n\nInstead of typing the arguments and return values with `React.FormEvent\u003c\u003e` and `void`, you may alternatively apply types to the event handler itself (_contributed by @TomasHubelbauer_):\n\n```tsx\n  // typing on LEFT hand side of =\n  onChange: React.ChangeEventHandler\u003cHTMLInputElement\u003e = (e) =\u003e {\n    this.setState({text: e.currentTarget.value})\n  }\n```\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003eWhy two ways to do the same thing?\u003c/b\u003e\u003c/summary\u003e\n\nThe first method uses an inferred method signature `(e: React.FormEvent\u003cHTMLInputElement\u003e): void` and the second method enforces a type of the delegate provided by `@types/react`. So `React.ChangeEventHandler\u003c\u003e` is simply a \"blessed\" typing by `@types/react`, whereas you can think of the inferred method as more... _artisanally hand-rolled_. Either way it's a good pattern to know. [See our Github PR for more](https://github.com/typescript-cheatsheets/react/pull/24).\n\n\u003c/details\u003e\n\n**Typing onSubmit, with Uncontrolled components in a Form**\n\nIf you don't quite care about the type of the event, you can just use `React.SyntheticEvent`. If your target form has custom named inputs that you'd like to access, you can use a type assertion:\n\n```tsx\n\u003cform\n  ref={formRef}\n  onSubmit={(e: React.SyntheticEvent) =\u003e {\n    e.preventDefault();\n    const target = e.target as typeof e.target \u0026 {\n      email: { value: string };\n      password: { value: string };\n    };\n    const email = target.email.value; // typechecks!\n    const password = target.password.value; // typechecks!\n    // etc...\n  }}\n\u003e\n  \u003cdiv\u003e\n    \u003clabel\u003e\n      Email:\n      \u003cinput type=\"email\" name=\"email\" /\u003e\n    \u003c/label\u003e\n  \u003c/div\u003e\n  \u003cdiv\u003e\n    \u003clabel\u003e\n      Password:\n      \u003cinput type=\"password\" name=\"password\" /\u003e\n    \u003c/label\u003e\n  \u003c/div\u003e\n  \u003cdiv\u003e\n    \u003cinput type=\"submit\" value=\"Log in\" /\u003e\n  \u003c/div\u003e\n\u003c/form\u003e\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtCAOwGctoRlM4BeRYmAOgFc6kLABQBKClVoM4AMSbs4o9gD4FFOHAA8mJmrhFMbAN7aozJJgC+u2gGVeAIxDAYRoUgBcndDxsBPGjAAFkgwwGgAogBuSAEiynCGuupI3GBE0QEAIuYovAA2MKIA3Elw1PTwMChQAOYh8ilVtfUodHAwvmBIEKyN1XXwAGQJpckgKMB5noZwkSh5vB5wDFDANDVwFiXk6rtwYK10AO7QACbTs-OLnitrG1ulDzu75VJI45PyTQPc7xN53DmCyQRTgAHowe1Okg0ME0ABrOgAQlKr3gBzoxzOX36IVShxOUFOgKuIPBkI6XVhMMRKOe6ghcBCaG4rN0Fis5CUug0p2AkW59M0eRQ9iQeUFe3U4Q+U1GmjWYF4lWhbAARH9Jmq4DQUCAkOrNXltWDJbsNGCRWKJTywXyBTz7Wb1BoreLnbsAAoEs7ueUaRXKqFddUYrFE7W6-Whn0R8Eei1um3PC1Ox38hOBlUhtV0BxOGDaoGLdUAGQgGzWJrNqYzFAtJhAgpEQA)\n\nOf course, if you're making any sort of significant form, [you should use Formik](https://jaredpalmer.com/formik) or [React Hook Form](https://react-hook-form.com/), which are written in TypeScript.\n\n##### List of event types\n\n| Event Type       | Description                                                                                                                                                                                                                                                            |\n| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| AnimationEvent   | CSS Animations.                                                                                                                                                                                                                                                        |\n| ChangeEvent      | Changing the value of `\u003cinput\u003e`, `\u003cselect\u003e` and `\u003ctextarea\u003e` element.                                                                                                                                                                                                  |\n| ClipboardEvent   | Using copy, paste and cut events.                                                                                                                                                                                                                                      |\n| CompositionEvent | Events that occur due to the user indirectly entering text (e.g. depending on Browser and PC setup, a popup window may appear with additional characters if you e.g. want to type Japanese on a US Keyboard)                                                           |\n| DragEvent        | Drag and drop interaction with a pointer device (e.g. mouse).                                                                                                                                                                                                          |\n| FocusEvent       | Event that occurs when elements gets or loses focus.                                                                                                                                                                                                                   |\n| FormEvent        | Event that occurs whenever a form or form element gets/loses focus, a form element value is changed or the form is submitted.                                                                                                                                          |\n| InvalidEvent     | Fired when validity restrictions of an input fails (e.g `\u003cinput type=\"number\" max=\"10\"\u003e` and someone would insert number 20).                                                                                                                                          |\n| KeyboardEvent    | User interaction with the keyboard. Each event describes a single key interaction.                                                                                                                                                                                     |\n| MouseEvent       | Events that occur due to the user interacting with a pointing device (e.g. mouse)                                                                                                                                                                                      |\n| PointerEvent     | Events that occur due to user interaction with a variety pointing of devices such as mouse, pen/stylus, a touchscreen and which also supports multi-touch. Unless you develop for older browsers (IE10 or Safari 12), pointer events are recommended. Extends UIEvent. |\n| TouchEvent       | Events that occur due to the user interacting with a touch device. Extends UIEvent.                                                                                                                                                                                    |\n| TransitionEvent  | CSS Transition. Not fully browser supported. Extends UIEvent                                                                                                                                                                                                           |\n| UIEvent          | Base Event for Mouse, Touch and Pointer events.                                                                                                                                                                                                                        |\n| WheelEvent       | Scrolling on a mouse wheel or similar input device. (Note: `wheel` event should not be confused with the `scroll` event)                                                                                                                                               |\n| SyntheticEvent   | The base event for all above events. Should be used when unsure about event type                                                                                                                                                                                       |\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eWhat about \u003ccode\u003eInputEvent\u003c/code\u003e?\u003c/b\u003e\u003c/summary\u003e\n\nYou've probably noticed that there is no `InputEvent`. This is because it is not supported by Typescript as the event itself has no fully browser support and may behave differently in different browsers. You can use `KeyboardEvent` instead.\n\nSources:\n\n- https://github.com/microsoft/TypeScript/issues/29441\n- https://developer.mozilla.org/en-US/docs/Web/API/InputEvent\n- https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event\n\n\u003c/details\u003e\n\n\u003c!--END-SECTION:forms-and-events--\u003e\n\n\u003c!--START-SECTION:context--\u003e\n\n#### Context\n\n#### Basic example\n\nHere's a basic example of creating a context containing the active theme.\n\n```tsx\nimport { createContext } from \"react\";\n\ntype ThemeContextType = \"light\" | \"dark\";\n\nconst ThemeContext = createContext\u003cThemeContextType\u003e(\"light\");\n```\n\nWrap the components that need the context with a context provider:\n\n```tsx\nimport { useState } from \"react\";\n\nconst App = () =\u003e {\n  const [theme, setTheme] = useState\u003cThemeContextType\u003e(\"light\");\n\n  return (\n    \u003cThemeContext.Provider value={theme}\u003e\n      \u003cMyComponent /\u003e\n    \u003c/ThemeContext.Provider\u003e\n  );\n};\n```\n\nCall `useContext` to read and subscribe to the context.\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () =\u003e {\n  const theme = useContext(ThemeContext);\n\n  return \u003cp\u003eThe current theme is {theme}.\u003c/p\u003e;\n};\n```\n\n#### Without default context value\n\nIf you don't have any meaningful default value, specify `null`:\n\n```tsx\nimport { createContext } from \"react\";\n\ninterface CurrentUserContextType {\n  username: string;\n}\n\nconst CurrentUserContext = createContext\u003cCurrentUserContextType | null\u003e(null);\n```\n\n```tsx\nconst App = () =\u003e {\n  const [currentUser, setCurrentUser] = useState\u003cCurrentUserContextType\u003e({\n    username: \"filiptammergard\",\n  });\n\n  return (\n    \u003cCurrentUserContext.Provider value={currentUser}\u003e\n      \u003cMyComponent /\u003e\n    \u003c/CurrentUserContext.Provider\u003e\n  );\n};\n```\n\nNow that the type of the context can be `null`, you'll notice that you'll get a `'currentUser' is possibly 'null'` TypeScript error if you try to access the `username` property. You can use optional chaining to access `username`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () =\u003e {\n  const currentUser = useContext(CurrentUserContext);\n\n  return \u003cp\u003eName: {currentUser?.username}.\u003c/p\u003e;\n};\n```\n\nHowever, it would be preferable to not have to check for `null`, since we know that the context won't be `null`. One way to do that is to provide a custom hook to use the context, where an error is thrown if the context is not provided:\n\n```tsx\nimport { createContext } from \"react\";\n\ninterface CurrentUserContextType {\n  username: string;\n}\n\nconst CurrentUserContext = createContext\u003cCurrentUserContextType | null\u003e(null);\n\nconst useCurrentUser = () =\u003e {\n  const currentUserContext = useContext(CurrentUserContext);\n\n  if (!currentUserContext) {\n    throw new Error(\n      \"useCurrentUser has to be used within \u003cCurrentUserContext.Provider\u003e\"\n    );\n  }\n\n  return currentUserContext;\n};\n```\n\nUsing a runtime type check in this will has the benefit of printing a clear error message in the console when a provider is not wrapping the components properly. Now it's possible to access `currentUser.username` without checking for `null`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () =\u003e {\n  const currentUser = useCurrentUser();\n\n  return \u003cp\u003eUsername: {currentUser.username}.\u003c/p\u003e;\n};\n```\n\n##### Type assertion as an alternative\n\nAnother way to avoid having to check for `null` is to use type assertion to tell TypeScript you know the context is not `null`:\n\n```tsx\nimport { useContext } from \"react\";\n\nconst MyComponent = () =\u003e {\n  const currentUser = useContext(CurrentUserContext);\n\n  return \u003cp\u003eName: {currentUser!.username}.\u003c/p\u003e;\n};\n```\n\nAnother option is to use an empty object as default value and cast it to the expected context type:\n\n```tsx\nconst CurrentUserContext = createContext\u003cCurrentUserContextType\u003e(\n  {} as CurrentUserContextType\n);\n```\n\nYou can also use non-null assertion to get the same result:\n\n```tsx\nconst CurrentUserContext = createContext\u003cCurrentUserContextType\u003e(null!);\n```\n\nWhen you don't know what to choose, prefer runtime checking and throwing over type asserting.\n\n\u003c!--END-SECTION:context--\u003e\n\n\u003c!--START-SECTION:forward-create-ref--\u003e\n\n#### forwardRef/createRef\n\nCheck the [Hooks section](https://github.com/typescript-cheatsheets/react/blob/main/README.md#hooks) for `useRef`.\n\n`createRef`:\n\n```tsx\nimport { createRef, PureComponent } from \"react\";\n\nclass CssThemeProvider extends PureComponent\u003cProps\u003e {\n  private rootRef = createRef\u003cHTMLDivElement\u003e(); // like this\n  render() {\n    return \u003cdiv ref={this.rootRef}\u003e{this.props.children}\u003c/div\u003e;\n  }\n}\n```\n\n`forwardRef`:\n\n```tsx\nimport { forwardRef, ReactNode } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n  type: \"submit\" | \"button\";\n}\nexport type Ref = HTMLButtonElement;\n\nexport const FancyButton = forwardRef\u003cRef, Props\u003e((props, ref) =\u003e (\n  \u003cbutton ref={ref} className=\"MyClassName\" type={props.type}\u003e\n    {props.children}\n  \u003c/button\u003e\n));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eSide note: the \u003ccode\u003eref\u003c/code\u003e you get from \u003ccode\u003eforwardRef\u003c/code\u003e is mutable so you can assign to it if needed.\u003c/b\u003e\u003c/summary\u003e\n\nThis was done [on purpose](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43265/). You can make it immutable if you have to - assign `React.Ref` if you want to ensure nobody reassigns it:\n\n```tsx\nimport { forwardRef, ReactNode, Ref } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n  type: \"submit\" | \"button\";\n}\n\nexport const FancyButton = forwardRef(\n  (\n    props: Props,\n    ref: Ref\u003cHTMLButtonElement\u003e // \u003c-- here!\n  ) =\u003e (\n    \u003cbutton ref={ref} className=\"MyClassName\" type={props.type}\u003e\n      {props.children}\n    \u003c/button\u003e\n  )\n);\n```\n\n\u003c/details\u003e\n\nIf you are grabbing the props of a component that forwards refs, use [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770).\n\n#### Generic forwardRefs\n\nRead more context in https://fettblog.eu/typescript-react-generic-forward-refs/:\n\n##### Option 1 - Wrapper component\n\n```ts\ntype ClickableListProps\u003cT\u003e = {\n  items: T[];\n  onSelect: (item: T) =\u003e void;\n  mRef?: React.Ref\u003cHTMLUListElement\u003e | null;\n};\n\nexport function ClickableList\u003cT\u003e(props: ClickableListProps\u003cT\u003e) {\n  return (\n    \u003cul ref={props.mRef}\u003e\n      {props.items.map((item, i) =\u003e (\n        \u003cli key={i}\u003e\n          \u003cbutton onClick={(el) =\u003e props.onSelect(item)}\u003eSelect\u003c/button\u003e\n          {item}\n        \u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  );\n}\n```\n\n##### Option 2 - Redeclare forwardRef\n\n```ts\n// Redeclare forwardRef\ndeclare module \"react\" {\n  function forwardRef\u003cT, P = {}\u003e(\n    render: (props: P, ref: React.Ref\u003cT\u003e) =\u003e React.ReactElement | null\n  ): (props: P \u0026 React.RefAttributes\u003cT\u003e) =\u003e React.ReactElement | null;\n}\n\n// Just write your components like you're used to!\nimport { forwardRef, ForwardedRef } from \"react\";\n\ninterface ClickableListProps\u003cT\u003e {\n  items: T[];\n  onSelect: (item: T) =\u003e void;\n}\n\nfunction ClickableListInner\u003cT\u003e(\n  props: ClickableListProps\u003cT\u003e,\n  ref: ForwardedRef\u003cHTMLUListElement\u003e\n) {\n  return (\n    \u003cul ref={ref}\u003e\n      {props.items.map((item, i) =\u003e (\n        \u003cli key={i}\u003e\n          \u003cbutton onClick={(el) =\u003e props.onSelect(item)}\u003eSelect\u003c/button\u003e\n          {item}\n        \u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  );\n}\n\nexport const ClickableList = forwardRef(ClickableListInner);\n```\n\n##### Option 3 - Call signature\n\n```ts\n// Add to `index.d.ts`\ninterface ForwardRefWithGenerics extends React.FC\u003cWithForwardRefProps\u003cOption\u003e\u003e {\n  \u003cT extends Option\u003e(props: WithForwardRefProps\u003cT\u003e): ReturnType\u003c\n    React.FC\u003cWithForwardRefProps\u003cT\u003e\u003e\n  \u003e;\n}\n\nexport const ClickableListWithForwardRef: ForwardRefWithGenerics =\n  forwardRef(ClickableList);\n```\n\nCredits: https://stackoverflow.com/a/73795494\n\n#### More Info\n\n- https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315\n\nYou may also wish to do [Conditional Rendering with `forwardRef`](https://github.com/typescript-cheatsheets/react/issues/167).\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n\u003c!--END-SECTION:forward-create-ref--\u003e\n\n\u003c!--START-SECTION:portals--\u003e\n\n#### Portals\n\nUsing `ReactDOM.createPortal`:\n\n```tsx\nconst modalRoot = document.getElementById(\"modal-root\") as HTMLElement;\n// assuming in your html file has a div with id 'modal-root';\n\nexport class Modal extends React.Component\u003c{ children?: React.ReactNode }\u003e {\n  el: HTMLElement = document.createElement(\"div\");\n\n  componentDidMount() {\n    modalRoot.appendChild(this.el);\n  }\n\n  componentWillUnmount() {\n    modalRoot.removeChild(this.el);\n  }\n\n  render() {\n    return ReactDOM.createPortal(this.props.children, this.el);\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWRYmAEQHkBZObXAo9GAWgBNcZchTQQAdgGd4ICHxQAbBBAjwAvHAFoAriCRiYAOgDmSGAFF5SXfoBCATwCSfABQAiGXPk8cK1wEo4FAk4AAkAFWYAGQsrPRgAbgoAeiTAiQkdYDEjOCy4OwgtKDgACxgQeTZgS1KgwI1gADc4AHdgGBLcvgIPBW9lGHxE4XIkAA9qeDR5IODmWQU4cZg9PmDkbgMAYVxIMTi4AG8KOCX5AC5QiOjLazUNCG07gzQuFZi7tz4m-2GTuFE4HEcXowD48y0+mcAWO5FOp16igGBhQYDAqy2JWqLg6wAkBiQ8j8w1OAF8KP9AXs4gB1aryACqYhkkJg0KO-wRCyRKgMRBkjSQmOxzlx+MJxP+5JGpyIYj4SCg7Nh8LgRBgRTEtG4TGYLzeSAACtAYApRVj8WAcGB8WgsfI+HKADRwMUEokkuDS0lAA)\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cb\u003eUsing hooks\u003c/b\u003e\u003c/summary\u003e\n\nSame as above but using hooks\n\n```tsx\nimport { useEffect, useRef, ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\nconst modalRoot = document.querySelector(\"#modal-root\") as HTMLElement;\n\ntype ModalProps = {\n  children: ReactNode;\n};\n\nfunction Modal({ children }: ModalProps) {\n  // create div element only once using ref\n  const elRef = useRef\u003cHTMLDivElement | null\u003e(null);\n  if (!elRef.current) elRef.current = document.createElement(\"div\");\n\n  useEffect(() =\u003e {\n    const el = elRef.current!; // non-null assertion because it will never be null\n    modalRoot.appendChild(el);\n    return () =\u003e {\n      modalRoot.removeChild(el);\n    };\n  }, []);\n\n  return createPortal(children, elRef.current);\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzkgKIBmZSG2RSyZ2y6MAchACZJwC+cZUEEHADkUVBmEBYAFChIsXHDRiUMJAAVoMFABsefAUNHiYAWnaCp0mQHobcFIUL4QwAHYBzOO7gBPCPhQcAAWMCB6ZMA6XMGODnDswABucADuwDDB3uwiIBy6pgIQMMIA3DJoEG6E8HnsuggQxXAAvAkQaC5IbjAAdACO+EhQvgDKSNEY0AAUAEQAxHUFRTCzAJQOhHAAEgAqALIAMiTRIN0w5dbSML5gXPv5OuoCYFttODJwSsFR7GJuAC5ECY2JxLtxLjIyPg3BhgFU4A96jppng0D8dH9ujwgUjdM8IK8Nh9pF87EoVGoEsk4BMkGcenAqjpfEzYVwiO4vGIyJ8lFUarSdPRWgRiPQADx7I4AEWSJ3p5zgAB84G58DodAA+abqzVrS5fYBkODTACEE3ovU6UH+MA2lqQZGtgTtoosnQZfWUqDUCq9c0SSXWkNJYtIFCoMGm0w2LS1uD5X0q1XgE1FjudNrtZtKcHJbiqpj1ekcxFg8LccAARlQULRvPB0pq1UgksMa1wS0m4EthU0+igwHc3OwAMIY9jTCYGntiGCBKux1oJklfde9x6NYq9MR5dsT37TnSzsNfCF87jYADaAF1T3z54uKb6NFpdNN0b9-thMy7becp7cDIIHSOSRAoB4SCgdCsIwJWcAAILDsua78qmcDXoQwQQKkeI6NgxAwKMOF4Y8t6ikwGC9LQozaGo0xkLoxCnl8T5QEuPYSkGWo9mS9j+PgSgoFWzEQHAYD4PAmTAFsPiCUENSqMAaAhGEERRNBZ7rtxNLAOwLSzH2hQDrMWoSjYPF8bg2G4fhcAAGQOaa1lfBK+G8dpG5uUGrneTUvjRC0OBod5YXUoQYA6CgvhArMHhQPpsyYH5YVRegSAAJJqCAhBxWg5zDMlqXecESDAB4oRxQAjAADLVSTBMVXnhV86TsJkQLCHVDXBMIKUta11boAA1glASjnFUAeMN0y1Zg82Lb01VrM1rVhQAXplo5IAAHkCACcB0Det67cMBg3rp5p1fJlwhCCgm7ImaOCzHAswXTdcAStWUkwAiAVBSFw1oGNAgwuwcVgEOvgoKkPxgB9vBVGOOgqSNwXLvGcBESRdmPIxzFIGs3BamgOgQMQFm-TA-1uNd60WVZl0WR51kk9ZP1-QiKNo6DmNxgmuOkfh0wwFAQwk1qtmpIijzU9z9PWeSYiChAJoKQ4w5cZZyQM2sMjcEAA)\n\n\u003c/details\u003e\n\nModal Component Usage Example:\n\n```tsx\nimport { useState } from \"react\";\n\nfunction App() {\n  const [showModal, setShowModal] = useState(false);\n\n  return (\n    \u003cdiv\u003e\n      // you can also put this in your static html file\n      \u003cdiv id=\"modal-root\"\u003e\u003c/div\u003e\n      {showModal \u0026\u0026 (\n        \u003cModal\u003e\n          \u003cdiv\n            style={{\n              display: \"grid\",\n              placeItems: \"center\",\n              height: \"100vh\",\n              width: \"100vh\",\n              background: \"rgba(0,0,0,0.1)\",\n              zIndex: 99,\n            }}\n          \u003e\n            I'm a modal!{\" \"}\n            \u003cbutton\n              style={{ background: \"papyawhip\" }}\n              onClick={() =\u003e setShowModal(false)}\n            \u003e\n              close\n            \u003c/button\u003e\n          \u003c/div\u003e\n        \u003c/Modal\u003e\n      )}\n      \u003cbutton onClick={() =\u003e setShowModal(true)}\u003eshow Modal\u003c/button\u003e\n      // rest of your app\n    \u003c/div\u003e\n  );\n}\n```\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003eContext of Example\u003c/b\u003e\u003c/summary\u003e\n\nThis example is based on the [Event Bubbling Through Portal](https://reactjs.org/docs/portals.html#event-bubbling-through-portals) example of React docs.\n\n\u003c/details\u003e\n\n\u003c!--END-SECTION:portals--\u003e\n\n\u003c!--START-SECTION:error-boundaries--\u003e\n\n#### Error Boundaries\n\n##### Option 1: Using react-error-boundary\n\n[React-error-boundary](https://github.com/bvaughn/react-error-boundary) - is a lightweight package ready to use for this scenario with TS support built-in.\nThis approach also lets you avoid class components that are not that popular anymore.\n\n##### Option 2: Writing your custom error boundary component\n\nIf you don't want to add a new npm package for this, you can also write your own `ErrorBoundary` component.\n\n```jsx\nimport React, { Component, ErrorInfo, ReactNode } from \"react\";\n\ninterface Props {\n  children?: ReactNode;\n}\n\ninterface State {\n  hasError: boolean;\n}\n\nclass ErrorBoundary extends Component\u003cProps, State\u003e {\n  public state: State = {\n    hasError: false\n  };\n\n  public static getDerivedStateFromError(_: Error): State {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true };\n  }\n\n  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n    console.error(\"Uncaught error:\", error, errorInfo);\n  }\n\n  public render() {\n    if (this.state.hasError) {\n      return \u003ch1\u003eSorry.. there was an error\u003c/h1\u003e;\n    }\n\n    return this.props.children;\n  }\n}\n\nexport default ErrorBoundary;\n\n```\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n\u003c!--END-SECTION:error-boundaries--\u003e\n\n\u003c!--START-SECTION:concurrent--\u003e\n\n#### Concurrent React/React Suspense\n\n_Not written yet._ watch \u003chttps://github.com/sw-yx/fresh-async-react\u003e for more on React Suspense and Time Slicing.\n\n[Something to add? File an issue](https://github.com/typescript-cheatsheets/react/issues/new).\n\n\u003c!--END-SECTION:concurrent--\u003e\n\n\u003c!--START-SECTION:types--\u003e\n\n### Troubleshooting Handbook: Types\n\n\u003e ⚠️ Have you read [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ?) Your answer might be there!\n\nFacing weird type errors? You aren't alone. This is the hardest part of using TypeScript with React. Be patient - you are learning a new language after all. However, the more you get good at this, the less time you'll be working _against_ the compiler and the more the compiler will be working _for_ you!\n\nTry to avoid typing with `any` as much as possible to experience the full benefits of TypeScript. Instead, let's try to be familiar with some of the common strategies to solve these issues.\n\n#### Union Types and Type Guarding\n\nUnion types are handy for solving some of these typing problems:\n\n```tsx\nclass App extends React.Component\u003c\n  {},\n  {\n    count: number | null; // like this\n  }\n\u003e {\n  state = {\n    count: null,\n  };\n  render() {\n    return \u003cdiv onClick={() =\u003e this.increment(1)}\u003e{this.state.count}\u003c/div\u003e;\n  }\n  increment = (amt: number) =\u003e {\n    this.setState((state) =\u003e ({\n      count: (state.count || 0) + amt,\n    }));\n  };\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2K0EAK48YALjg89IAEZIocAD6m91agG44AejdxqwANZI4MAAWwHSaKhQAfFrkinQwKNxwALzRijr6hiZmTmHOmkT81gAUAJSpaUQwelA8cLJ8wABucBA8Yt5oPklKpclRQSEiwDxoRCAyRQCMJSoRSgN0InEJSCK6BjAqsm4NjRF5MXDhh8OjSOOGyXBFKCDGDpbWZUlRStoBwYt0SDAAyvHcIrLRIva5vQ5pODrTLXYGraHwWz2AAMZQA1HBbjB3ioSiUDooVAcVEA)\n\n**Type Guarding**: Sometimes Union Types solve a problem in one area but create another downstream. If `A` and `B` are both object types, `A | B` isn't \"either A or B\", it is \"A or B or both at once\", which causes some confusion if you expected it to be the former. Learn how to write checks, guards, and assertions (also see the Conditional Rendering section below). For example:\n\n```ts\ninterface Admin {\n  role: string;\n}\ninterface User {\n  email: string;\n}\n\n// Method 1: use `in` keyword\nfunction redirect(user: Admin | User) {\n  if (\"role\" in user) {\n    // use the `in` operator for typeguards since TS 2.7+\n    routeToAdminPage(user.role);\n  } else {\n    routeToHomePage(user.email);\n  }\n}\n\n// Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enough\nfunction isAdmin(user: Admin | User): user is Admin {\n  return (user as any).role !== undefined;\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoC4AOxiSk3STgEEATEGuAbwrjhwAbJAC44AZxhQaAcwDcFAL5Va9RmmYBVcfR584SECmCCxk6dXlKKFTAFdqGYBGoCIdugBUI7TtQAKKDJIABTiwDLUwJjA9ACUeuT80XBhEVExugC8OQR2OlAIEML4CbxJ-AJIMHZQrvi+NGQVinDWlOT2jjDOrjgeSN4AErhIgcFpkdGxUGX6KZMZM3A5WQSGxoKliZVVNXUEIyBIYEFIzfzK5FcUAPS3cACy1QAWEGxwAIxi+cwABjQ-nAANZIACeAHdoGxbA4nC4qmxgEQMCFflAxI1XAAfODaeI7ODREIAIiESBJRNc6LKcHucF+cBgL3+gLgEDA9BQMGgcEwvJgYM5MjsKCgbHEEhoGjgngAynAAEwAOgA7ABqfT8fpeHwcGjjULo5XkuIKFoGQQ6Qna9y6o5jM5ogrKjYmM36K43cj057M95KsRofI8vCCzlwEVitgAGjgbAgSElzOY4hQxyZL1kVPZgjYunlcAAbvRwi5JbyISyiHAAdQgcBxLQDNR3DIXrDur0ieIsc76Jj9Ti8QU4j8Cj3WEPCUR9q5+1A4ChJShqGC4ibiswAIS5Bz5mLUJAw65AA)\n\nMethod 2 is also known as [User-Defined Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) and can be really handy for readable code. This is how TS itself refines types with `typeof` and `instanceof`.\n\nIf you need `if...else` chains or the `switch` statement instead, it should \"just work\", but look up [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions) if you need help. (See also: [Basarat's writeup](https://basarat.gitbook.io/typescript/type-system/discriminated-unions)). This is handy in typing reducers for `useReducer` or Redux.\n\n#### Optional Types\n\nIf a component has an optional prop, add a question mark and assign during destructure (or use defaultProps).\n\n```tsx\nclass MyComponent extends React.Component\u003c{\n  message?: string; // like this\n}\u003e {\n  render() {\n    const { message = \"default\" } = this.props;\n    return \u003cdiv\u003e{message}\u003c/div\u003e;\n  }\n}\n```\n\nYou can also use a `!` character to assert that something is not undefined, but this is not encouraged.\n\n_Something to add? [File an issue](https://github.com/typescript-cheatsheets/react/issues/new) with your suggestions!_\n\n#### Enum Types\n\n**We recommend avoiding using enums as far as possible**.\n\nEnums have a few [documented issues](https://fettblog.eu/tidy-typescript-avoid-enums/) (the TS team [agrees](https://twitter.com/orta/status/1348966323271987201?s=20)). A simpler alternative to enums is just declaring a union type of string literals:\n\n```tsx\nexport declare type Position = \"left\" | \"right\" | \"top\" | \"bottom\";\n```\n\nIf you must use enums, remember that enums in TypeScript default to numbers. You will usually want to use them as strings instead:\n\n```tsx\nexport enum ButtonSizes {\n  default = \"default\",\n  small = \"small\",\n  large = \"large\",\n}\n\n// usage\nexport const PrimaryButton = (\n  props: Props \u0026 React.HTMLProps\u003cHTMLButtonElement\u003e\n) =\u003e \u003cButton size={ButtonSizes.default} {...props} /\u003e;\n```\n\n#### Type Assertion\n\nSometimes you know better than TypeScript that the type you're using is narrower than it thinks, or union types need to be asserted to a more specific type to work with other APIs, so assert with the `as` keyword. This tells the compiler you know better than it does.\n\n```tsx\nclass MyComponent extends React.Component\u003c{\n  message: string;\n}\u003e {\n  render() {\n    const { message } = this.props;\n    return (\n      \u003cComponent2 message={message as SpecialMessageType}\u003e{message}\u003c/Component2\u003e\n    );\n  }\n}\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgGU61gUAbAWSQGduUBzJABVa9ALwFuMKMAB2-fAG4KFOTCRRM6egAUcYbnADeFOHBA8+ggFxwpM+XAA+cAK6yAJkkxykH5eQAvirkaBCyUnAAwriQskiyMABMtsjoMAB0AGJRADx6EAYAfHASABRG5pYCSIEAlKUlZaZwuR7AAG5FLWa5ABYAjEVGFrw1gbkA9IPd5L2T7V0UdSFobCi8cBzUMeDhCfBIAB7qnoZpGBm7cQe5JnNVYzZ20nL8AYEl92ZEnhplDW+ZjgYQi8Eqoys9ECpTgMD6wG4GTA+m4AWBcCIMFcUFkcGaDwxuWu+0SSUeULEI2qgjgG0YzFYnBpwlEn2pT1qUxJ8TJswxdXRcGCQSAA)\n\nNote that you cannot assert your way to anything - basically it is only for refining types. Therefore it is not the same as \"casting\" a type.\n\nYou can also assert a property is non-null, when accessing it:\n\n```ts\nelement.parentNode!.removeChild(element); // ! before the period\nmyFunction(document.getElementById(dialog.id!)!); // ! after the property accessing\nlet userID!: string; // definite assignment assertion... be careful!\n```\n\nOf course, try to actually handle the null case instead of asserting :)\n\n#### Simulating Nominal Types\n\nTS' structural typing is handy, until it is inconvenient. However you can simulate nominal typing with [`type branding`](https://basarat.gitbook.io/typescript/main-1/nominaltyping):\n\n```ts\ntype OrderID = string \u0026 { readonly brand: unique symbol };\ntype UserID = string \u0026 { readonly brand: unique symbol };\ntype ID = OrderID | UserID;\n```\n\nWe can create these values with the Companion Object Pattern:\n\n```ts\nfunction OrderID(id: string) {\n  return id as OrderID;\n}\nfunction UserID(id: string) {\n  return id as UserID;\n}\n```\n\nNow TypeScript will disallow you from using the wrong ID in the wrong place:\n\n```ts\nfunction queryForUser(id: UserID) {\n  // ...\n}\nqueryForUser(OrderID(\"foobar\")); // Error, Argument of type 'OrderID' is not assignable to parameter of type 'UserID'\n```\n\nIn future you can use the `unique` keyword to brand. [See this PR](https://github.com/microsoft/TypeScript/pull/33038).\n\n#### Intersection Types\n\nAdding two types together can be handy, for example when your component is supposed to mirror the props of a native component like a `button`:\n\n```tsx\nexport interface PrimaryButtonProps {\n  label: string;\n}\nexport const PrimaryButton = (\n  props: PrimaryButtonProps \u0026 React.ButtonHTMLAttributes\u003cHTMLButtonElement\u003e\n) =\u003e {\n  // do custom buttony stuff\n  return \u003cbutton {...props}\u003e {props.label} \u003c/button\u003e;\n};\n```\n\n_Playground [here](https://www.typescriptlang.org/play?ssl=4\u0026ssc=1\u0026pln=12\u0026pc=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCipAD0ljmADsYkpN0k4AFKUFKAE8AQgFcYMCE14QwAZzgBvCnDgAbFACMkagFxw5MPkwDmAbgoBfanWjw0Uwzz4gBI8ZKZwAvHAAUKnBgOPL6vPxCYhJSMvJwAGSIxDAAdFGeABIAKgCyADIAghJ8muJIcgA82fnpUgCiakggSCwAfBQAlD6tSoEA9H1wACYQcGiihrhwpdFMggYwopiYgUSLUF4VM55KKXvBsnKWPYoH8ika2mqWcBV921KtFuSWQA)_\n\nYou can also use Intersection Types to make reusable subsets of props for similar components:\n\n```tsx\ntype BaseProps = {\n   className?: string,\n   style?: React.CSSProperties\n   name: string // used in both\n}\ntype DogProps = {\n  tailsCount: number\n}\ntype HumanProps = {\n  handsCount: number\n}\nexport const Human = (props: BaseProps \u0026 HumanProps) =\u003e // ...\nexport const Dog = (props: BaseProps \u0026 DogProps) =\u003e // ...\n```\n\n[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgCEUBnJABRzGbgF44BvCnGFoANi2YA5FCCQB+AFxxmMKMAB2AcwA0Q4Suqj5S5OhgA6AMIBlaxwh1YwJMz1x1MpEpVqtcAPT+cACurAAmcBpwAEYQMAAWFAC+VLT0ACIQmvZcvAJ6MCjAosyWEMHqMErqwSDRSFDJqXRwABK1KOo53HyC5MLxnWGl5ZXVtfWN5CnkSAAekLBwaBDqKm0d6ibEFgBilgA8TKzdcABkGyCd3QB8eQAUAJS8d-d6B2HAAG4BNxSPFAo80W8BWa3gmU02zM5n2RxY7E43AukNuD2ePFe70+P38f3IjyAA)\n\nMake sure not to confuse Intersection Types (which are **and** operations) with Union Types (which are **or** operations).\n\n#### Union Types\n\nThis section is yet to be written (please contribute!). Meanwhile, see our [commentary on Union Types usecases](https://github.com/typescript-cheatsheets/react/blob/main/README.md#union-types-and-type-guarding).\n\nThe ADVANCED cheatsheet also has information on Discriminated Union Types, which are helpful when TypeScript doesn't seem to be narrowing your union type as you expect.\n\n#### Overloading Function Types\n\nSpecifically when it comes to functions, you may need to overload instead of union type. The most common way function types are written uses the shorthand:\n\n```ts\ntype FunctionType1 = (x: string, y: number) =\u003e number;\n```\n\nBut this doesn't let you do any overloading. If you have the implementation, you can put them after each other with the function keyword:\n\n```ts\nfunction pickCard(x: { suit: string; card: number }[]): number;\nfunction pickCard(x: number): { suit: string; card: number };\nfunction pickCard(x): any {\n  // implementation with combined signature\n  // ...\n}\n```\n\nHowever, if you don't have an implementation and are just writing a `.d.ts` definition file, this won't help you either. In this case you can forego any shorthand and write them the old-school way. The key thing to remember here is as far as TypeScript is concerned, `functions are just callable objects with no key`:\n\n```ts\ntype pickCard = {\n  (x: { suit: string; card: number }[]): number;\n  (x: number): { suit: string; card: number };\n  // no need for combined signature in this form\n  // you can also type static properties of functions here eg `pickCard.wasCalled`\n};\n```\n\nNote that when you implement the actual overloaded function, the implementation will need to declare the combined call signature that you'll be handling, it won't be inferred for you. You can readily see examples of overloads in DOM APIs, e.g. `createElement`.\n\n[Read more about Overloading in the Handbook.](https://www.typescriptlang.org/docs/handbook/functions.html#overloads)\n\n#### Using Inferred Types\n\nLeaning on TypeScript's Type Inference is great... until you realize you need a type that was inferred, and have to go back and explicitly declare types/interfaces so you can export them for reuse.\n\nFortunately, with `typeof`, you won't have to do that. Just use it on any value:\n\n```tsx\nconst [state, setState] = useState({\n  foo: 1,\n  bar: 2,\n}); // state's type inferred to be {foo: number, bar: number}\n\nconst someMethod = (obj: typeof state) =\u003e {\n  // grabbing the type of state even though it was inferred\n  // some code using obj\n  setState(obj); // this works\n};\n```\n\n#### Using Partial Types\n\nWorking with slicing state and props is common in React. Again, you don't really have to go and explicitly redefine your types if you use the `Partial` generic type:\n\n```tsx\nconst [state, setState] = useState({\n  foo: 1,\n  bar: 2,\n}); // state's type inferred to be {foo: number, bar: number}\n\n// NOTE: stale state merging is not actually encouraged in useState\n// we are just demonstrating how to use Partial here\nconst partialStateUpdate = (obj: Partial\u003ctypeof state\u003e) =\u003e\n  setState({ ...state, ...obj });\n\n// later on...\npartialStateUpdate({ foo: 2 }); // this works\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eMinor caveats on using \u003ccode\u003ePartial\u003c/code\u003e\u003c/b\u003e\u003c/summary\u003e\n\nNote that there are some TS users who don't agree with using `Partial` as it behaves today. See [subtle pitfalls of the above example here](https://twitter.com/ferdaber/status/1084798596027957248), and check out this long discussion on [why @types/react uses Pick instead of Partial](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365).\n\n\u003c/details\u003e\n\n#### The Types I need weren't exported!\n\nThis can be annoying but here are ways to grab the types!\n\n- Grabbing the Prop types of a component: Use `React.ComponentProps` and `typeof`, and optionally `Omit` any overlapping types\n\n```tsx\nimport { Button } from \"library\"; // but doesn't export ButtonProps! oh no!\ntype ButtonProps = React.ComponentProps\u003ctypeof Button\u003e; // no problem! grab your own!\ntype AlertButtonProps = Omit\u003cButtonProps, \"onClick\"\u003e; // modify\nconst AlertButton = (props: AlertButtonProps) =\u003e (\n  \u003cButton onClick={() =\u003e alert(\"hello\")} {...props} /\u003e\n);\n```\n\nYou may also use [`ComponentPropsWithoutRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L774) (instead of ComponentProps) and [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770) (if your component specifically forwards refs)\n\n- Grabbing the return type of a function: use `ReturnType`:\n\n```tsx\n// inside some library - return type { baz: number } is inferred but not exported\nfunction foo(bar: string) {\n  return { baz: 1 };\n}\n\n//  inside your app, if you need { baz: number }\ntype FooReturn = ReturnType\u003ctypeof foo\u003e; // { baz: number }\n```\n\nIn fact you can grab virtually anything public: [see this blogpost from Ivan Koshelev](http://ikoshelev.azurewebsites.net/search/id/11/Pragmatic-uses-of-TypeScript-type-system-My-type-of-type)\n\n```ts\nfunction foo() {\n  return {\n    a: 1,\n    b: 2,\n    subInstArr: [\n      {\n        c: 3,\n        d: 4,\n      },\n    ],\n  };\n}\n\ntype InstType = ReturnType\u003ctypeof foo\u003e;\ntype SubInstArr = InstType[\"subInstArr\"];\ntype SubInstType = SubInstArr[0];\n\nlet baz: SubInstType = {\n  c: 5,\n  d: 6, // type checks ok!\n};\n\n//You could just write a one-liner,\n//But please make sure it is forward-readable\n//(you can understand it from reading once left-to-right with no jumps)\ntype SubInstType2 = ReturnType\u003ctypeof foo\u003e[\"subInstArr\"][0];\nlet baz2: SubInstType2 = {\n  c: 5,\n  d: 6, // type checks ok!\n};\n```\n\n- TS also ships with a `Parameters` utility type for extracting the parameters of a function\n- for anything more \"custom\", the `infer` keyword is the basic building block for this, but takes a bit of getting used to. Look at the source code for the above utility types, and [this example](https://twitter.com/mgechev/status/1211030455224422401?s=20) to get the idea. Basarat [also has a good video on `infer`](https://www.youtube.com/watch?v=ijK-1R-LFII\u0026list=PLYvdvJlnTOjF6aJsWWAt7kZRJvzw-en8B\u0026index=3\u0026t=0s).\n\n#### The Types I need don't exist!\n\nWhat's more annoying than modules with unexported types? Modules that are **untyped**!\n\n\u003e Before you proceed - make sure you have checked that types don't exist in [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) or [TypeSearch](https://microsoft.github.io/TypeSearch/)\n\nFret not! There are more than a couple of ways in which you can solve this problem.\n\n##### Slapping `any` on everything\n\nA **lazier** way would be to create a new type declaration file, say `typedec.d.ts`– if you don't already have one. Ensure that the path to file is resolvable by TypeScript by checking the `include` array in the `tsconfig.json` file at the root of your directory.\n\n```json\n// inside tsconfig.json\n{\n  // ...\n  \"include\": [\n    \"src\" // automatically resolves if the path to declaration is src/typedec.d.ts\n  ]\n  // ...\n}\n```\n\nWithin this file, add the `declare` syntax for your desired module, say `my-untyped-module`– to the declaration file:\n\n```ts\n// inside typedec.d.ts\ndeclare module \"my-untyped-module\";\n```\n\nThis one-liner alone is enough if you just need it to work without errors. A even hackier, write-once-and-forget way would be to use `\"*\"` instead which would then apply the `Any` type for all existing and future untyped modules.\n\nThis solution works well as a workaround if you have less than a couple untyped modules. Anything more, you now have a ticking type-bomb in your hands. The only way of circumventing this problem would be to define the missing types for those untyped modules as explained in the following sections.\n\n##### Autogenerate types\n\nYou can use TypeScript with `--allowJs` and `--declaration` to see TypeScript's \"best guess\" at the types of the library.\n\nIf this doesn't work well enough, use [`dts-gen`](https://github.com/Microsoft/dts-gen) to use the runtime shape of the object to accurately enumerate all available properties. This tends to be very accurate, BUT the tool does not yet support scraping JSDoc comments to populate additional types.\n\n```bash\nnpm install -g dts-gen\ndts-gen -m \u003cyour-module\u003e\n```\n\nThere are other automated JS to TS conversion tools and migration strategies - see [our MIGRATION cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/migration/from_js).\n\n##### Typing Exported Hooks\n\nTyping Hooks is just like typing pure functions.\n\nThe following steps work under two assumptions:\n\n- You have already created a type declaration file as stated earlier in the section.\n- You have access to the source code - specifically the code that directly exports the functions you will be using. In most cases, it would be housed in an `index.js` file.\n  Typically you need a minimum of **two** type declarations (one for **Input Prop** and the other for **Return Prop**) to define a hook completely. Suppose the hook you wish to type follows the following structure,\n\n```js\n// ...\nconst useUntypedHook = (prop) =\u003e {\n  // some processing happens here\n  return {\n    /* ReturnProps */\n  };\n};\nexport default useUntypedHook;\n```\n\nthen, your type declaration should most likely follow the following syntax.\n\n```ts\ndeclare module 'use-untyped-hook' {\n  export interface InputProps { ... }   // type declaration for prop\n  export interface ReturnProps { ... } // type declaration for return props\n  export default function useUntypedHook(\n    prop: InputProps\n    // ...\n  ): ReturnProps;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eFor instance, the \u003ca href=\"https://github.com/donavon/use-dark-mode\"\u003euseDarkMode hook\u003c/a\u003e exports the functions that follows a similar structure.\u003c/b\u003e\u003c/summary\u003e\n\n```js\n// inside src/index.js\nconst useDarkMode = (\n  initialValue = false, // -\u003e input props / config props to be exported\n  {\n    // -\u003e input props / config props to be exported\n    element,\n    classNameDark,\n    classNameLight,\n    onChange,\n    storageKey = \"darkMode\",\n    storageProvider,\n    global,\n  } = {}\n) =\u003e {\n  // ...\n  return {\n    // -\u003e return props to be exported\n    value: state,\n    enable: useCallback(() =\u003e setState(true), [setState]),\n    disable: useCallback(() =\u003e setState(false), [setState]),\n    toggle: useCallback(() =\u003e setState((current) =\u003e !current), [setState]),\n  };\n};\nexport default useDarkMode;\n```\n\nAs the comments suggest, exporting these config props and return props following the aforementioned structure will result in the following type export.\n\n```ts\ndeclare module \"use-dark-mode\" {\n  /**\n   * A config object allowing you to specify certain aspects of `useDarkMode`\n   */\n  export interface DarkModeConfig {\n    classNameDark?: string; // A className to set \"dark mode\". Default = \"dark-mode\".\n    classNameLight?: string; // A className to set \"light mode\". Default = \"light-mode\".\n    element?: HTMLElement; // The element to apply the className. Default = `document.body`\n    onChange?: (val?: boolean) =\u003e void; // Override the default className handler with a custom callback.\n    storageKey?: string; // Specify the `localStorage` key. Default = \"darkMode\". Set to `null` to disable persistent storage.\n    storageProvider?: WindowLocalStorage; // A storage provider. Default = `localStorage`.\n    global?: Window; // The global object. Default = `window`.\n  }\n  /**\n   * An object returned from a call to `useDarkMode`.\n   */\n  export interface DarkMode {\n    readonly value: boolean;\n    enable: () =\u003e void;\n    disable: () =\u003e void;\n    toggle: () =\u003e void;\n  }\n  /**\n   * A custom React Hook to help you implement a \"dark mode\" component for your application.\n   */\n  export default function useDarkMode(\n    initialState?: boolean,\n    config?: DarkModeConfig\n  ): DarkMode;\n}\n```\n\n\u003c/details\u003e\n\n##### Typing Exported Components\n\nIn case of typing untyped class components, there's almost no difference in approach except for the fact that after declaring the types, you export the extend the type using `class UntypedClassComponent extends React.Component\u003cUntypedClassComponentProps, any\u003e {}` where `UntypedClassComponentProps` holds the type declaration.\n\nFor instance, [sw-yx's Gist on React Router 6 types](https://gist.github.com/sw-yx/37a6a3d248c2d4031801f0d568904df8) implemented a similar method for typing the then untyped RR6.\n\n```ts\ndeclare module \"react-router-dom\" {\n  import * as React from 'react';\n  // ...\n  type NavigateProps\u003cT\u003e = {\n    to: string | number,\n    replace?: boolean,\n    state?: T\n  }\n  //...\n  export class Navigate\u003cT = any\u003e extends React.Component\u003cNavigateProps\u003cT\u003e\u003e{}\n  // ...\n```\n\nFor more information on creating type definitions for class components, you can refer to this [post](https://templecoding.com/blog/2016/03/31/creating-typescript-typings-for-existing-react-components) for reference.\n\n#### Frequent Known Problems with TypeScript\n\nJust a list of stuff that React developers frequently run into, that TS has no solution for. Not necessarily TSX only.\n\n##### TypeScript doesn't narrow after an object element null check\n\n[![https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg\u0026name=medium](https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg\u0026name=medium)](https://mobile.twitter.com/tannerlinsley/status/1390409931627499523)\n\nRef: https://mobile.twitter.com/tannerlinsley/status/1390409931627499523. see also https://github.com/microsoft/TypeScript/issues/9998\n\n##### TypeScript doesn't let you restrict the type of children\n\nGuaranteeing typesafety for this kind of API isn't possible:\n\n```tsx\n\u003cMenu\u003e\n  \u003cMenuItem/\u003e {/* ok */}\n  \u003cMenuLink/\u003e {/* ok */}\n  \u003cdiv\u003e {/* error */}\n\u003c/Menu\u003e\n```\n\nSource: https://twitter.com/ryanflorence/status/1085745787982700544?s=20\n\n\u003c!--END-SECTION:types--\u003e\n\n\u003c!--START-SECTION:operators--\u003e\n\n### Troubleshooting Handbook: Operators\n\n- `typeof` and `instanceof`: type query used for refinement\n- `keyof`: get keys of an object. `keyof T` is an operator to tell you what values of `k` can be used for `obj[k]`.\n  - [Some misconceptions here](https://twitter.com/SeaRyanC/status/1418678670739218438?s=20).\n- `O[K]`: property lookup\n- `[K in O]`: mapped types\n- `+` or `-` or `readonly` or `?`: addition and subtraction and readonly and optional modifiers\n- `x ? Y : Z`: Conditional types for generic types, type aliases, function parameter types\n- `!`: Nonnull assertion for nullable types\n- `=`: Generic type parameter default for generic types\n- `as`: type assertion\n- `is`: type guard for function return types\n\nConditional Types are a difficult topic to get around so here are some extra resources:\n\n- fully walked through explanation https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/\n- Bailing out and other advanced topics https://github.com/sw-yx/ts-spec/blob/master/conditional-types.md\n- Basarat's video https://www.youtube.com/watch?v=SbVgPQDealg\u0026list=PLYvdvJlnTOjF6aJsWWAt7kZRJvzw-en8B\u0026index=2\u0026t=0s\n- [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ\u0026feature=youtu.be)\n\n\u003c!--END-SECTION:operators--\u003e\n\n\u003c!--START-SECTION:utilities--\u003e\n\n### Troubleshooting Handbook: Utilities\n\nThese are all built in, [see source in es5.d.ts](https://github.com/microsoft/TypeScript/blob/33a34e5b96bfe086266f4765ab9789a2a02507f9/src/lib/es5.d.ts#L1523-L1637):\n\n- `Awaited`: emulate the behavior of `await`\n- `Capitalize`: convert first character of string literal type to uppercase\n- `ConstructorParameters`: a tuple of class constructor's parameter types\n- `Exclude`: exclude a type from another type\n- `Extract`: select a subtype that is assignable to another type\n- `InstanceType`: the instance type you get from a `new`ing a class constructor\n- `Lowercase`: convert string literal type to lowercase\n- `NonNullable`: exclude `null` and `undefined` from a type\n- `Omit`: construct a type with the properties of another type.\n- `OmitThisParameter`: remove the 'this' parameter from a function type.\n- `Parameters`: a tuple of a function's parameter types\n- `Partial`: Make all properties in an object optional\n- `Readonly`: Make all properties in an object readonly\n- `ReadonlyArray`: Make an immutable array of the given type\n- `Pick`: A subtype of an object type with a subset of its keys\n- `Record`: A map from a key type to a value type\n- `Required`: Make all properties in an object required\n- `ReturnType`: A function's return type\n- `ThisParameterType`: extract the type of the 'this' parameter of a function type\n- `ThisType`: marker for contextual 'this' type\n- `Uncapitalize`: convert first character of string literal type to lowercase\n- `Uppercase`: convert string literal type to uppercase\n\n\u003c!--END-SECTION:utilities--\u003e\n\n\u003c!--START-SECTION:ts-config--\u003e\n\n### Troubleshooting Handbook: tsconfig.json\n\nYou can find [all the Compiler options in the TypeScript docs](https://www.typescriptlang.org/docs/handbook/compiler-options.html). [The new TS docs also has per-flag annotations of what each does](https://www.typescriptlang.org/tsconfig#allowSyntheticDefaultImports). This is the setup I roll with for APPS (not libraries - for libraries you may wish to see the settings we use in `tsdx`):\n\n```json\n{\n  \"compilerOptions\": {\n    \"incremental\": true,\n    \"outDir\": \"build/lib\",\n    \"target\": \"es5\",\n    \"module\": \"esnext\",\n    \"lib\": [\"DOM\", \"ESNext\"],\n    \"sourceMap\": true,\n    \"importHelpers\": true,\n    \"declaration\": true,\n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noImplicitReturns\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"allowJs\": false,\n    \"jsx\": \"react\",\n    \"moduleResolution\": \"node\",\n    \"baseUrl\": \"src\",\n    \"forceConsistentCasingInFileNames\": true,\n    \"esModuleInterop\": true,\n    \"suppressImplicitAnyIndexErrors\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"experimentalDecorators\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"build\", \"scripts\"]\n}\n```\n\nYou can find more [recommended TS config here](https://github.com/tsconfig/bases).\n\nPlease open an issue and discuss if there are better recommended choices for React.\n\nSelected flags and why we like them:\n\n- `esModuleInterop`: disables namespace imports (`import * as foo from \"foo\"`) and enables CJS/AMD/UMD style imports (`import fs from \"fs\"`)\n- `strict`: `strictPropertyInitialization` forces you to initialize class properties or explicitly declare that they can be undefined. You can opt out of this with a definite assignment assertion.\n- `\"typeRoots\": [\"./typings\", \"./node_modules/@types\"]`: By default, TypeScript looks in `node_modules/@types` and parent folders for third party type declarations. You may wish to override this default resolution so you can put all your global type declarations in a special `typings` folder.\n\nCompilation time grows linearly with size of codebase. For large projects, you will want to use [Project References](https://www.typescriptlang.org/docs/handbook/project-references.html). See our [ADVANCED](https://react-typescript-cheatsheet.netlify.app/docs/advanced) cheatsheet for commentary.\n\n\u003c!--END-SECTION:ts-config--\u003e\n\n\u003c!--START-SECTION:official-typings-bugs--\u003e\n\n### Troubleshooting Handbook: Fixing bugs in official typings\n\nIf you run into bugs with your library's official typings, you can copy them locally and tell TypeScript to use your local version using the \"paths\" field. In your `tsconfig.json`:\n\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"mobx-react\": [\"../typings/modules/mobx-react\"]\n    }\n  }\n}\n```\n\n[Thanks to @adamrackis for the tip.](https://twitter.com/AdamRackis/status/1024827730452520963)\n\nIf you just need to add an interface, or add missing members to an existing interface, you don't need to copy the whole typing package. Instead, you can use [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html):\n\n```tsx\n// my-typings.ts\ndeclare module \"plotly.js\" {\n  interface PlotlyHTMLElement {\n    removeAllListeners(): void;\n  }\n}\n\n// MyComponent.tsx\nimport { PlotlyHTMLElement } from \"plotly.js\";\n\nconst f = (e: PlotlyHTMLElement) =\u003e {\n  e.removeAllListeners();\n};\n```\n\nYou don't always have to implement the module, you can simply import the module as `any` for a quick start:\n\n```tsx\n// my-typings.ts\ndeclare module \"plotly.js\"; // each of its imports are `any`\n```\n\nBecause you don't have to explicitly import this, this is known as an [ambient module declaration](https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html#pitfalls-of-namespaces-and-modules). You can do AMD's in a script-mode `.ts` file (no imports or exports), or a `.d.ts` file anywhere in your project.\n\nYou can also do ambient variable and ambient type declarations:\n\n```ts\n// ambient utility type\ntype ToArray\u003cT\u003e = T extends unknown[] ? T : T[];\n// ambient variable\ndeclare let process: {\n  env: {\n    NODE_ENV: \"development\" | \"production\";\n  };\n};\nprocess = {\n  env: {\n    NODE_ENV: \"production\",\n  },\n};\n```\n\nYou can see examples of these included in the built in type declarations in the `lib` field of `tsconfig.json`\n\n\u003c!--END-SECTION:official-typings-bugs--\u003e\n\n\u003c!--START-SECTION:non-ts-files--\u003e\n\n### Troubleshooting Handbook: Globals, Images and other non-TS files\n\nUse [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).\n\nIf, say, you are using a third party JS script that attaches on to the `window` global, you can extend `Window`:\n\n```ts\ndeclare global {\n  interface Window {\n    MyVendorThing: MyVendorType;\n  }\n}\n```\n\nLikewise if you wish to \"import\" an image or other non TS/TSX file:\n\n```ts\n// declaration.d.ts\n// anywhere in your project, NOT the same name as any of your .ts/tsx files\ndeclare module \"*.png\";\n\n// importing in a tsx file\nimport * as logo from \"./logo.png\";\n```\n\nNote that `tsc` cannot bundle these files for you, you will have to use Webpack or Parcel.\n\nRelated issue: https://github.com/Microsoft/TypeScript-React-Starter/issues/12 and [StackOverflow](https://stackoverflow.com/a/49715468/4216035)\n\n\u003c!--END-SECTION:non-ts-files--\u003e\n\n\u003c!--START-SECTION:editor-integration--\u003e\n\n### Editor Tooling and Integration\n\n- VSCode\n  - swyx's VSCode Extension: https://github.com/sw-yx/swyx-react-typescript-snippets\n  - amVim: https://marketplace.visualstudio.com/items?itemName=auiworks.amvim\n- VIM\n  - https://github.com/Quramy/tsuquyomi\n  - nvim-typescript?\n  - https://github.com/leafgarland/typescript-vim\n  - peitalin/vim-jsx-typescript\n  - NeoVim: https://github.com/neoclide/coc.nvim\n  - other discussion: https://mobile.twitter.com/ryanflorence/status/1085715595994095620\n\nYou are free to use this repo's TSX logo if you wish:\n\n[![https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png](https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png)](https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png)\n\nYou may also wish to use alternative logos - [jsx-tsx-logos](https://github.com/Protectator/jsx-tsx-logos)\n\n![https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png](https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png)\n\n\u003c!--END-SECTION:editor-integration--\u003e\n\n\u003c!--START-SECTION:linting--\u003e\n\n### Linting\n\n\u003e ⚠️Note that [TSLint is now in maintenance and you should try to use ESLint instead](https://medium.com/palantir/tslint-in-2019-1a144c2317a9). If you are interested in TSLint tips, please check this PR from [@azdanov](https://github.com/typescript-cheatsheets/react/pull/14). The rest of this section just focuses on ESLint. [You can convert TSlint to ESlint with this tool](https://github.com/typescript-eslint/tslint-to-eslint-config).\n\n\u003e ⚠️This is an evolving topic. `typescript-eslint-parser` is no longer maintained and [work has recently begun on `typescript-eslint` in the ESLint community](https://eslint.org/blog/2019/01/future-typescript-eslint) to bring ESLint up to full parity and interop with TSLint.\n\nFollow the TypeScript + ESLint docs at https://github.com/typescript-eslint/typescript-eslint:\n\n```\nyarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint\n```\n\nadd a `lint` script to your `package.json`:\n\n```json\n  \"scripts\": {\n    \"lint\": \"eslint 'src/**/*.ts'\"\n  },\n```\n\nand a suitable `.eslintrc.js` (using `.js` over `.json` here so we can add comments):\n\n```js\nmodule.exports = {\n  env: {\n    es6: true,\n    node: true,\n    jest: true,\n  },\n  extends: \"eslint:recommended\",\n  parser: \"@typescript-eslint/parser\",\n  plugins: [\"@typescript-eslint\"],\n  parserOptions: {\n    ecmaVersion: 2017,\n    sourceType: \"module\",\n  },\n  rules: {\n    indent: [\"error\", 2],\n    \"linebreak-style\": [\"error\", \"unix\"],\n    quotes: [\"error\", \"single\"],\n    \"no-console\": \"warn\",\n    \"no-unused-vars\": \"off\",\n    \"@typescript-eslint/no-unused-vars\": [\n      \"error\",\n      { vars: \"all\", args: \"after-used\", ignoreRestSiblings: false },\n    ],\n    \"@typescript-eslint/explicit-function-return-type\": \"warn\", // Consider using explicit annotations for object literals and function return types even when they can be inferred.\n    \"no-empty\": \"warn\",\n  },\n};\n```\n\nMost of this is taken from [the `tsdx` PR](https://github.com/palmerhq/tsdx/pull/70/files) which is for **libraries**.\n\nMore `.eslintrc.json` options to consider with more options you may want for **apps**:\n\n```json\n{\n  \"extends\": [\n    \"airbnb\",\n    \"prettier\",\n    \"prettier/react\",\n    \"plugin:prettier/recommended\",\n    \"plugin:jest/recommended\",\n    \"plugin:unicorn/recommended\"\n  ],\n  \"plugins\": [\"prettier\", \"jest\", \"unicorn\"],\n  \"parserOptions\": {\n    \"sourceType\": \"module\",\n    \"ecmaFeatures\": {\n      \"jsx\": true\n    }\n  },\n  \"env\": {\n    \"es6\": true,\n    \"browser\": true,\n    \"jest\": true\n  },\n  \"settings\": {\n    \"import/resolver\": {\n      \"node\": {\n        \"extensions\": [\".js\", \".jsx\", \".ts\", \".tsx\"]\n      }\n    }\n  },\n  \"overrides\": [\n    {\n      \"files\": [\"**/*.ts\", \"**/*.tsx\"],\n      \"parser\": \"typescript-eslint-parser\",\n      \"rules\": {\n        \"no-undef\": \"off\"\n      }\n    }\n  ]\n}\n```\n\nAnother great resource is [\"Using ESLint and Prettier in a TypeScript Project\"](https://dev.to/robertcoopercode/using-eslint-and-prettier-in-a-typescript-project-53jb) by @robertcoopercode.\n\nWes Bos is also working on [TypeScript support for his eslint+prettier config.](https://github.com/wesbos/eslint-config-wesbos/issues/68)\n\nIf you're looking for information on Prettier, check out the [Prettier](https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/misc-concerns.md#prettier) guide.\n\n\u003c!--END-SECTION:linting--\u003e\n\n\u003c!--START-SECTION:resources--\u003e\n\n### Other React + TypeScript resources\n\n- me! \u003chttps://twitter.com/swyx\u003e\n- https://www.freecodecamp.org/news/how-to-build-a-todo-app-with-react-typescript-nodejs-and-mongodb/\n- \u003chttps://github.com/piotrwitek/react-redux-typescript-guide\u003e - **HIGHLY HIGHLY RECOMMENDED**, i wrote this repo before knowing about this one, this has a lot of stuff I don't cover, including **REDUX** and **JEST**.\n- [10 Bad TypeScript Habits](https://startup-cto.net/10-bad-typescript-habits-to-break-this-year/):\n  1. not using `\"strict\": true`\n  2. using `||` for default values when we have `??`\n  3. Using `any` instead of `unknown` for API responses\n  4. using `as` assertion instead of Type Guards (`function isFoo(obj: unknown): obj is Foo {}`)\n  5. `as any` in tests\n  6. Marking optional properties instead of modeling which combinations exist by extending interfaces\n  7. One letter generics\n  8. Non-boolean `if (nonboolean)` checks\n  9. bangbang checks `if (!!nonboolean)`\n  10. `!= null` to check for `null` and `undefined`\n- [Ultimate React Component Patterns with TypeScript 2.8](https://levelup.gitconnected.com/ultimate-react-component-patterns-with-typescript-2-8-82990c516935)\n- [Basarat's TypeScript gitbook has a React section](https://basarat.gitbook.io/typescript/tsx/react) with an [Egghead.io course](https://egghead.io/courses/use-typescript-to-develop-react-applications) as well.\n- [Palmer Group's TypeScript + React Guidelines](https://github.com/palmerhq/typescript) as well as Jared's other work like [disco.chat](https://github.com/jaredpalmer/disco.chat)\n- [Sindre Sorhus' TypeScript Style Guide](https://github.com/sindresorhus/typescript-definition-style-guide)\n- [TypeScript React Starter Template by Microsoft](https://github.com/Microsoft/TypeScript-React-Starter) A starter template for TypeScript and React with a detailed README describing how to use the two together. Note: this doesn't seem to be frequently updated anymore.\n- [Steve Kinney's React and TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/react-typescript/)\n- [Brian Holt's Intermediate React course on Frontend Masters (paid)](https://frontendmasters.com/courses/intermediate-react/converting-the-app-to-typescript/) - Converting App To TypeScript Section\n- [Mike North's Production TypeScript course on Frontend Masters (paid)](https://frontendmasters.com/courses/production-typescript/)\n- [TSX Guide](https://jenil.github.io/chota/) by [gojutin](https://github.com/gojutin/www.tsx.guide)\n- TypeScript conversion:\n  - [Lyft's React-To-TypeScript conversion CLI](https://github.com/lyft/react-javascript-to-typescript-transform)\n  - [Gustav Wengel's blogpost - converting a React codebase to TypeScript](http://www.gustavwengel.dk/converting-typescript-to-javascript-part-1)\n  - [Microsoft React TypeScript conversion guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide)\n- [Matt Pocock's Beginner's Typescript Tutorial](https://github.com/total-typescript/beginners-typescript-tutorial)\n- [Matt Pocock's React with TypeScript Tutorial](https://www.totaltypescript.com/tutorials/react-with-typescript)\n- [You?](https://github.com/typescript-cheatsheets/react/issues/new).\n\n\u003c!--END-SECTION:resources--\u003e\n\n\u003c!--START-SECTION:talks--\u003e\n\n### Recommended React + TypeScript talks\n\n- [Ultimate React Component Patterns with TypeScript](https://www.youtube.com/watch?v=_PBQ3if6Fmg), by Martin Hochel, GeeCon Prague 2018\n- [How to Build React Apps with TypeScript](https://youtu.be/LJzGGmu5APA?si=YNzy7T_8yj7TuXxS), by ClearEdge Tech Talk 2022\n- [Create a More Readable React Codebase Using TypeScript](https://youtu.be/nkJbGgieALI?si=IFZZIMEiXz7AsiBv), by Emma Brillhart 2019\n- [Advanced TypeScript with React](https://youtu.be/zQfD4ZxxyKA?si=FmrgOq667svX6C9O), by Nikhil Verma 2019\n- [Senior Typescript Features You don't Know About - clean-code](https://www.youtube.com/watch?v=Y4u97vJqmhM), by CoderOne 2023\n- [React \u0026 TypeScript - Course for Beginners](https://www.youtube.com/watch?v=FJDVKeh7RJI), by FreeCodeCamp 2022\n- [TypeScript + React](https://www.youtube.com/watch?v=1ZnrX3wiNTU), by Chris Toomey 2019\n- [Mastering React Hooks](https://www.youtube.com/watch?v=zM_ZiSl2n2E), by Jack Herrington 2021\n- [Using Hooks and codegen](https://www.youtube.com/watch?v=cdsnzfJUqm0) by Tejas Kumar 2019\n\n- Please help contribute to this new section!\n\n\u003c!--END-SECTION:talks--\u003e\n\n\u003c!--START-SECTION:learn-ts--\u003e\n\n### Time to Really Learn TypeScript\n\nBelieve it or not, we have only barely introduced TypeScript here in this cheatsheet. If you are still facing TypeScript troubleshooting issues, it is likely that your understanding of TS is still too superficial.\n\nThere is a whole world of generic type logic that you will eventually get into, however it becomes far less dealing with React than just getting good at TypeScript so it is out of scope here. But at least you can get productive in React now :)\n\nIt is worth mentioning some resources to help you get started:\n\n- Step through the 40+ examples under [the playground's](http://www.typescriptlang.org/play/index.html) Examples section, written by @Orta\n- Anders Hejlsberg's overview of TS: https://www.youtube.com/watch?v=ET4kT88JRXs\n- Marius Schultz: https://blog.mariusschulz.com/series/typescript-evolution with an [Egghead.io course](https://egghead.io/courses/advanced-static-types-in-typescript)\n- Basarat's Deep Dive: https://basarat.gitbook.io/typescript/\n- Axel Rauschmeyer's [Tackling TypeScript](https://exploringjs.com/tackling-ts/)\n- Rares Matei: [Egghead.io course](https://egghead.io/courses/practical-advanced-typescript)'s advanced TypeScript course on Egghead.io is great for newer typescript features and practical type logic applications (e.g. recursively making all properties of a type `readonly`)\n- Learn about [Generics, Conditional types and Mapped types](https://www.youtube.com/watch?v=PJjeHzvi_VQ\u0026feature=youtu.be)\n- Shu Uesugi: [TypeScript for Beginner Programmers](https://ts.chibicode.com/)\n- Here is another [TypeScript Error Guide](https://github.com/threehams/typescript-error-guide/) that you can check for your errors.\n\n\u003c!--END-SECTION:learn-ts--\u003e\n\n\u003c!--START-SECTION:examples--\u003e\n\n### Example App\n\n- [Create React App TypeScript Todo Example 2021](https://github.com/laststance/create-react-app-typescript-todo-example-2021)\n- [Ben Awad's 14 hour Fullstack React/GraphQL/TypeScript Tutorial](https://www.youtube.com/watch?v=I6ypD7qv3Z8)\n- [Cypress Realworld App](https://github.com/cypress-io/cypress-realworld-app)\n\n\u003c!--END-SECTION:examples--\u003e\n\n## My question isn't answered here!\n\n- [File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new).\n\n## Contributors\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. See [CONTRIBUTORS.md](/CONTRIBUTORS.md) for the full list. Contributions of any kind welcome!\n","funding_links":[],"categories":["JavaScript","Cheatsheets and Quick References","typescript","前端开发框架及项目","Cheat sheets","Uncategorized","cheatsheet"],"sub_categories":["其他_文本生成、文本对话","Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftypescript-cheatsheets%2Freact","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftypescript-cheatsheets%2Freact","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftypescript-cheatsheets%2Freact/lists"}