Skip to content

Commit

Permalink
Merge pull request #24 from TomasHubelbauer/patch-1
Browse files Browse the repository at this point in the history
Contribute an alternative typing example for forms sample
  • Loading branch information
swyxio authored Jun 8, 2018
2 parents f424a81 + 4672769 commit ea6419f
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,21 @@ class App extends React.Component<{}, { // no props
}
```

[Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
Instead of typing the arguments and return values with `React.FormEvent<>` and `void`, you may alternatively apply types to the event handler itself (*contributed by @TomasHubelbauer*):

```tsx
onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
this.setState({text: e.currentTarget.value})
}
```

<details>

<summary><b>Discussion</b></summary>

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).

</details>

# Section 3: Advanced Guides

Expand Down

0 comments on commit ea6419f

Please sign in to comment.