Skip to content

Commit ea81e1d

Browse files
authored
docs: Switch TS Events docs to use .currentTarget (#1241)
1 parent d8120b3 commit ea81e1d

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

content/en/guide/v10/typescript.md

+14-17
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: "Preact has built-in TypeScript support. Learn how to make use of i
55

66
# TypeScript
77

8-
Preact ships TypeScript type definitions, which are used by the library itself!
8+
Preact ships TypeScript type definitions, which are used by the library itself!
99

1010
When you use Preact in a TypeScript-aware editor (like VSCode), you can benefit from the added type information while writing regular JavaScript. If you want to add type information to your own applications, you can use [JSDoc annotations](https://fettblog.eu/typescript-jsdoc-superpowers/), or write TypeScript and transpile to regular JavaScript. This section will focus on the latter.
1111

@@ -233,35 +233,32 @@ Now when we use `Input` it will know about properties like `value`, ...
233233
Preact emits regular DOM events. As long as your TypeScript project includes the `dom` library (set it in `tsconfig.json`), you have access to all event types that are available in your current configuration.
234234

235235
```tsx
236+
import type { JSX } from "preact";
237+
236238
export class Button extends Component {
237-
handleClick(event: MouseEvent) {
238-
event.preventDefault();
239-
if (event.target instanceof HTMLElement) {
240-
alert(event.target.tagName); // Alerts BUTTON
241-
}
239+
handleClick(event: JSX.TargetedMouseEvent<HTMLButtonElement>) {
240+
alert(event.currentTarget.tagName); // Alerts BUTTON
242241
}
243242

244243
render() {
245-
return <button onClick={this.handleClick}>{this.props.children}</button>;
244+
return (
245+
<button onClick={this.handleClick}>
246+
{this.props.children}
247+
</button>
248+
);
246249
}
247250
}
248251
```
249252

250-
You can restrict event handlers by adding a type annotation for `this` to the function signature as the first argument. This argument will be erased after transpilation.
253+
If you prefer inline functions, you can forgo explicitly typing the current event target as it is inferred from the JSX element:
251254

252255
```tsx
253256
export class Button extends Component {
254-
// Adding the this argument restricts binding
255-
handleClick(this: HTMLButtonElement, event: MouseEvent) {
256-
event.preventDefault();
257-
if (event.target instanceof HTMLElement) {
258-
console.log(event.target.localName); // "button"
259-
}
260-
}
261-
262257
render() {
263258
return (
264-
<button onClick={this.handleClick}>{this.props.children}</button>
259+
<button onClick={(event) => alert(event.currentTarget.tagName)}>
260+
{this.props.children}
261+
</button>
265262
);
266263
}
267264
}

0 commit comments

Comments
 (0)