diff --git a/README.md b/README.md index 194c61ee..ddc6b6c1 100644 --- a/README.md +++ b/README.md @@ -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 = (e) => { + this.setState({text: e.currentTarget.value}) + } +``` + +
+ +Discussion + +Why two ways to do the same thing? The first method uses an inferred method signature `(e: React.FormEvent): 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). + +
# Section 3: Advanced Guides