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

+15-1
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)