Skip to content

Commit 21813ac

Browse files
Updated README on 2021-04-25T20:13:23.562Z
1 parent b25df79 commit 21813ac

File tree

1 file changed

+59
-34
lines changed

1 file changed

+59
-34
lines changed

README.md

Lines changed: 59 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,10 @@
158158
- [Using Partial Types](#using-partial-types)
159159
- [The Types I need weren't exported!](#the-types-i-need-werent-exported)
160160
- [The Types I need don't exist!](#the-types-i-need-dont-exist)
161-
- [Slapping `any` on everything](#slapping-any-on-everything)
162-
- [Autogenerate types](#autogenerate-types)
163-
- [Typing Exported Hooks](#typing-exported-hooks)
164-
- [Typing Exported Components](#typing-exported-components)<!--END-SECTION:types-toc-->
161+
* [Slapping `any` on everything](#slapping-any-on-everything)
162+
* [Autogenerate types](#autogenerate-types)
163+
* [Typing Exported Hooks](#typing-exported-hooks)
164+
* [Typing Exported Components](#typing-exported-components)<!--END-SECTION:types-toc-->
165165
- [Troubleshooting Handbook: Operators](#troubleshooting-handbook-operators)
166166
- [Troubleshooting Handbook: Utilties](#troubleshooting-handbook-utilities)
167167
- [Troubleshooting Handbook: tsconfig.json](#troubleshooting-handbook-tsconfigjson)
@@ -177,7 +177,6 @@
177177
</details>
178178

179179
<!--START-SECTION:setup-->
180-
181180
# Section 1: Setup TypeScript with React
182181

183182
## Prerequisites
@@ -255,7 +254,6 @@ You should also check [the new TypeScript docs for official descriptions between
255254
# Section 2: Getting Started
256255

257256
<!--START-SECTION:function-components-->
258-
259257
## Function Components
260258

261259
These can be written as normal functions that take a `props` argument and return a JSX element.
@@ -384,14 +382,13 @@ const MyArrayComponent = () => (Array(5).fill(<div />) as any) as JSX.Element;
384382
<!--END-SECTION:function-components-->
385383

386384
<!--START-SECTION:hooks-->
387-
388385
## Hooks
389386

390387
Hooks are [supported in `@types/react` from v16.8 up](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031).
391388

392389
## useState
393390

394-
Type inference works very well most of the time:
391+
Type inference works very well for simple values:
395392

396393
```tsx
397394
const [val, toggle] = React.useState(false);
@@ -410,6 +407,17 @@ const [user, setUser] = React.useState<IUser | null>(null);
410407
setUser(newUser);
411408
```
412409

410+
You can also use type assertions if a state is initialized soon after setup and always has a value after:
411+
412+
```tsx
413+
const [user, setUser] = React.useState<IUser>({} as IUser);
414+
415+
// later...
416+
setUser(newUser);
417+
```
418+
419+
This temporarily "lies" to the TypeScript compiler that `{}` is of type `IUser`. 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 `IUser` and that may lead to runtime errors.
420+
413421
## useReducer
414422

415423
You can use [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions) for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.
@@ -510,7 +518,7 @@ function DelayedEffect(props: { timerMs: number }) {
510518

511519
## useRef
512520

513-
When using `useRef`, you have three options when creating a ref container that does not have an initial value:
521+
When using `useRef`, you have two options when creating a ref container that does not have an initial value:
514522

515523
```ts
516524
const ref1 = useRef<HTMLElement>(null!);
@@ -668,7 +676,6 @@ If you are writing a React Hooks library, don't forget that you should also expo
668676
<!--END-SECTION:hooks-->
669677

670678
<!--START-SECTION:class-components-->
671-
672679
## Class Components
673680

674681
Within TypeScript, `React.Component` is a generic type (aka `React.Component<PropType, StateType>`), so you want to provide it with (optional) prop and state type parameters:
@@ -843,7 +850,6 @@ class Comp extends React.PureComponent<Props, State> {
843850
<!--END-SECTION:class-components-->
844851

845852
<!--START-SECTION:default-props-->
846-
847853
## You May Not Need `defaultProps`
848854

849855
As per [this tweet](https://twitter.com/dan_abramov/status/1133878326358171650), defaultProps will eventually be deprecated. You can check the discussions here:
@@ -1054,7 +1060,6 @@ The problem with this approach is it causes complex issues with the type inferen
10541060
<!--END-SECTION:default-props-->
10551061

10561062
<!--START-SECTION:basic-type-examples-->
1057-
10581063
## Typing Component Props
10591064

10601065
This is intended as a basic orientation and reference for React developers familiarizing with TypeScript.
@@ -1286,7 +1291,6 @@ class Comp extends React.PureComponent<Props, State> {
12861291
<!--END-SECTION:get-derived-state-from-props-->
12871292

12881293
<!--START-SECTION:forms-and-events-->
1289-
12901294
## Forms and Events
12911295

12921296
If performance is not an issue (and it usually isn't!), inlining handlers is easiest as you can just use [type inference and contextual typing](https://www.typescriptlang.org/docs/handbook/type-inference.html#contextual-typing):
@@ -1347,7 +1351,7 @@ The first method uses an inferred method signature `(e: React.FormEvent<HTMLInpu
13471351

13481352
**Typing onSubmit, with Uncontrolled components in a Form**
13491353

1350-
If you don't quite care about the type of the event, you can just use React.SyntheticEvent. If your target form has custom named inputs that you'd like to access, you can use type widening:
1354+
If you don't quite care about the type of the event, you can just use React.SyntheticEvent. If your target form has custom named inputs that you'd like to access, you can use a type assertion:
13511355

13521356
```tsx
13531357
<form
@@ -1385,10 +1389,47 @@ If you don't quite care about the type of the event, you can just use React.Synt
13851389

13861390
Of course, if you're making any sort of significant form, [you should use Formik](https://jaredpalmer.com/formik) or [React Hook Form](https://react-hook-form.com/), which are written in TypeScript.
13871391

1392+
### List of event types
1393+
1394+
| Event Type | Description |
1395+
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1396+
| AnimationEvent | CSS Animations. |
1397+
| ChangeEvent | Changing the value of `<input>`, `<select>` and `<textarea>` element. |
1398+
| ClipboardEvent | Using copy, paste and cut events. |
1399+
| 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) |
1400+
| DragEvent | Drag and drop interaction with a pointer device (e.g. mouse). |
1401+
| FocusEvent | Event that occurs when elements gets or loses focus. |
1402+
| FormEvent | Event that occurs whenever a form or form element gets/loses focus, a form element value is changed or the form is submitted. |
1403+
| InvalidEvent | Fired when validity restrictions of an input fails (e.g `<input type="number" max="10">` and someone would insert number 20). |
1404+
| KeyboardEvent | User interaction with the keyboard. Each event describes a single key interaction. |
1405+
| MouseEvent | Events that occur due to the user interacting with a pointing device (e.g. mouse) |
1406+
| 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. |
1407+
| TouchEvent | Events that occur due to the user interacting with a touch device. Extends UIEvent. |
1408+
| TransitionEvent | CSS Transition. Not fully browser supported. Extends UIEvent |
1409+
| UIEvent | Base Event for Mouse, Touch and Pointer events. |
1410+
| WheelEvent | Scrolling on a mouse wheel or similar input device. (Note: `wheel` event should not be confused with the `scroll` event) |
1411+
| SyntheticEvent | The base event for all above events. Should be used when unsure about event type |
1412+
1413+
<details>
1414+
<summary>
1415+
1416+
**What about `InputEvent`?**
1417+
1418+
</summary>
1419+
1420+
You'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.
1421+
1422+
Sources:
1423+
1424+
- https://github.com/microsoft/TypeScript/issues/29441
1425+
- https://developer.mozilla.org/en-US/docs/Web/API/InputEvent
1426+
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
1427+
1428+
</details>
1429+
13881430
<!--END-SECTION:forms-and-events-->
13891431

13901432
<!--START-SECTION:context-->
1391-
13921433
## Context
13931434

13941435
## Basic Example
@@ -1671,7 +1712,6 @@ const Consumer = Context.Consumer;
16711712
<!--END-SECTION:context-->
16721713

16731714
<!--START-SECTION:forward-create-ref-->
1674-
16751715
## forwardRef/createRef
16761716

16771717
Check the [Hooks section](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/blob/master/README.md#hooks) for `useRef`.
@@ -1734,7 +1774,6 @@ You may also wish to do [Conditional Rendering with `forwardRef`](https://github
17341774
<!--END-SECTION:forward-create-ref-->
17351775

17361776
<!--START-SECTION:portals-->
1737-
17381777
## Portals
17391778

17401779
Using `ReactDOM.createPortal`:
@@ -1844,7 +1883,6 @@ This example is based on the [Event Bubbling Through Portal](https://reactjs.org
18441883
<!--END-SECTION:portals-->
18451884

18461885
<!--START-SECTION:error-boundaries-->
1847-
18481886
## Error Boundaries
18491887

18501888
### Option 1: Using react-error-boundary
@@ -1899,7 +1937,6 @@ export default ErrorBoundary;
18991937
<!--END-SECTION:error-boundaries-->
19001938

19011939
<!--START-SECTION:concurrent-->
1902-
19031940
## Concurrent React/React Suspense
19041941

19051942
_Not written yet._ watch <https://github.com/sw-yx/fresh-async-react> for more on React Suspense and Time Slicing.
@@ -1909,7 +1946,6 @@ _Not written yet._ watch <https://github.com/sw-yx/fresh-async-react> for more o
19091946
<!--END-SECTION:concurrent-->
19101947

19111948
<!--START-SECTION:types-->
1912-
19131949
# Troubleshooting Handbook: Types
19141950

19151951
> ⚠️ Have you read [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ?) Your answer might be there!
@@ -2045,9 +2081,9 @@ Note that you cannot assert your way to anything - basically it is only for refi
20452081
You can also assert a property is non-null, when accessing it:
20462082

20472083
```ts
2048-
element.parentNode!.removeChild(element) // ! before the period
2049-
myFunction(document.getElementById(dialog.id!)! // ! after the property accessing
2050-
let userID!: string // definite assignment assertion... be careful!
2084+
element.parentNode!.removeChild(element); // ! before the period
2085+
myFunction(document.getElementById(dialog.id!)!); // ! after the property accessing
2086+
let userID!: string; // definite assignment assertion... be careful!
20512087
```
20522088

20532089
Of course, try to actually handle the null case instead of asserting :)
@@ -2455,7 +2491,6 @@ For more information on creating type definitions for class components, you can
24552491
<!--END-SECTION:types-->
24562492
24572493
<!--START-SECTION:operators-->
2458-
24592494
# Troubleshooting Handbook: Operators
24602495
24612496
- `typeof` and `instanceof`: type query used for refinement
@@ -2479,7 +2514,6 @@ Conditional Types are a difficult topic to get around so here are some extra res
24792514
<!--END-SECTION:operators-->
24802515
24812516
<!--START-SECTION:utilities-->
2482-
24832517
# Troubleshooting Handbook: Utilities
24842518
24852519
These are all built in, [see source in es5.d.ts](https://github.com/microsoft/TypeScript/blob/2c458c0d1ccb96442bca9ce43aa987fb0becf8a9/src/lib/es5.d.ts#L1401-L1474):
@@ -2501,7 +2535,6 @@ These are all built in, [see source in es5.d.ts](https://github.com/microsoft/Ty
25012535
<!--END-SECTION:utilities-->
25022536
25032537
<!--START-SECTION:ts-config-->
2504-
25052538
# Troubleshooting Handbook: tsconfig.json
25062539
25072540
You can find [all the Compiler options in the TypeScript docs](https://www.typescriptlang.org/docs/handbook/compiler-options.html). [The new TS docs also has per-flag annotations of what each does](https://www.typescriptlang.org/tsconfig#allowSyntheticDefaultImports). This is the setup I roll with for APPS (not libraries - for libraries you may wish to see the settings we use in `tsdx`):
@@ -2553,7 +2586,6 @@ Compilation speed grows linearly with size of codebase. For large projects, you
25532586
<!--END-SECTION:ts-config-->
25542587
25552588
<!--START-SECTION:official-typings-bugs-->
2556-
25572589
# Troubleshooting Handbook: Fixing bugs in official typings
25582590
25592591
If you run into bugs with your library's official typings, you can copy them locally and tell TypeScript to use your local version using the "paths" field. In your `tsconfig.json`:
@@ -2620,7 +2652,6 @@ You can see examples of these included in the built in type declarations in the
26202652
<!--END-SECTION:official-typings-bugs-->
26212653
26222654
<!--START-SECTION:non-ts-files-->
2623-
26242655
# Time to Really Learn TypeScript
26252656
26262657
Believe it or not, we have only barely introduced TypeScript here in this cheatsheet. If you are still facing TypeScript troubleshooting issues, it is likely that your understanding of TS is still too superficial.
@@ -2642,7 +2673,6 @@ It is worth mentioning some resources to help you get started:
26422673
<!--END-SECTION:non-ts-files-->
26432674
26442675
<!--START-SECTION:resources-->
2645-
26462676
# Other React + TypeScript resources
26472677
26482678
- me! <https://twitter.com/swyx>
@@ -2676,7 +2706,6 @@ It is worth mentioning some resources to help you get started:
26762706
<!--END-SECTION:resources-->
26772707
26782708
<!--START-SECTION:editor-integration-->
2679-
26802709
# Editor Tooling and Integration
26812710
26822711
- VSCode
@@ -2701,7 +2730,6 @@ You may also wish to use alternative logos - [jsx-tsx-logos](https://github.com/
27012730
<!--END-SECTION:editor-integration-->
27022731
27032732
<!--START-SECTION:linting-->
2704-
27052733
# Linting
27062734
27072735
> ⚠️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-typescript-cheatsheet/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).
@@ -2832,7 +2860,6 @@ If you're looking for information on Prettier, check out the [Prettier](https://
28322860
<!--END-SECTION:other-resources-->
28332861
28342862
<!--START-SECTION:talks-->
2835-
28362863
# Recommended React + TypeScript talks
28372864
28382865
- [Ultimate React Component Patterns with TypeScript](https://www.youtube.com/watch?v=_PBQ3if6Fmg), by Martin Hochel, GeeCon Prague 2018
@@ -2841,7 +2868,6 @@ If you're looking for information on Prettier, check out the [Prettier](https://
28412868
<!--END-SECTION:talks-->
28422869
28432870
<!--START-SECTION:learn-ts-->
2844-
28452871
# Time to Really Learn TypeScript
28462872
28472873
Believe it or not, we have only barely introduced TypeScript here in this cheatsheet. If you are still facing TypeScript troubleshooting issues, it is likely that your understanding of TS is still too superficial.
@@ -2863,7 +2889,6 @@ It is worth mentioning some resources to help you get started:
28632889
<!--END-SECTION:learn-ts-->
28642890
28652891
<!--START-SECTION:examples-->
2866-
28672892
# Example App
28682893
28692894
- [Create React App TypeScript Todo Example 2020](https://github.com/laststance/create-react-app-typescript-todo-example-2020)

0 commit comments

Comments
 (0)