Skip to content

Commit ea6419f

Browse files
authored
Merge pull request #24 from TomasHubelbauer/patch-1
Contribute an alternative typing example for forms sample
2 parents f424a81 + 4672769 commit ea6419f

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

README.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,21 @@ class App extends React.Component<{}, { // no props
369369
}
370370
```
371371

372-
[Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
372+
Instead of typing the arguments and return values with `React.FormEvent<>` and `void`, you may alternatively apply types to the event handler itself (*contributed by @TomasHubelbauer*):
373+
374+
```tsx
375+
onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
376+
this.setState({text: e.currentTarget.value})
377+
}
378+
```
379+
380+
<details>
381+
382+
<summary><b>Discussion</b></summary>
383+
384+
Why two ways to do the same thing? The first method uses an inferred method signature `(e: React.FormEvent<HTMLInputElement>): void` and the second method enforces a type of the delegate provided by `@types/react`. So `React.ChangeEventHandler<>` is simply a "blessed" typing by `@types/react`, whereas you can think of the inferred method as more... *artisanally hand-rolled*. Either way it's a good pattern to know. [See our Github PR for more](https://github.com/sw-yx/react-typescript-cheatsheet/pull/24).
385+
386+
</details>
373387

374388
# Section 3: Advanced Guides
375389

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy