Comments (4)
遭遇したエラーなど
どこから来たイベントかを判別するためにidから判別しようとしたが、e.target.idが使えない。
エラー文
プロパティ 'id' は型 'EventTarget' に存在しません。
コード
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
if (e.target.id === 'header-menu') {
}
};
解決策
e.target.id
=> e.currentTarget.id
.
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
if (e.currentTarget.id === 'header-menu') {
}
};
参考資料
from simple-markdown-editor-ts.
イベントハンドラを共通化する際、元のイベントハンドラで非同期処理を行っている場合の共通化手法
解決策
共通化するイベントハンドラを非同期処理可能なように記述する(個別にasyncを書かない)
コード
async function handleClick(event) {
// 共通の処理をここに記述する
// event.currentTarget.idに応じた処理
if (event.currentTarget.id === "element1") {
await asyncFunction1();
} else if (event.currentTarget.id === "element2") {
await asyncFunction2();
} else {
await asyncFunction3();
}
// その他の共通処理をここに記述する
}
参考文献
- ChatGPT
from simple-markdown-editor-ts.
関数を共通化する際、戻り値と引数が違う関数同士を共通化したい
手法検討
大きく分けて2つの方法がある。
- オーバーロードを使う。
- ジェネリクスを使う。
違い
- ユニオン型: 戻り値の型を変えないときに使う
- 関数のオーバーロード: 引数の型によって戻り値の型を変える必要があり、かつ引数にどんな型が入ってくるか明らかであるとき
- ジェネリクス: 引数にどんな型が入ってくるか明らかでないとき、もしくは引数の型と戻り値の型が直接結びついているとき
結論と所感
ジェネリクスを利用しようと思う。
どの関数を使っているかがわかりやすいし、コードの見通しが(個人的には)良くなる。
ただし戻り値と引数のテストは難しくなりそう…。
参考資料
- https://dev.to/pffigueiredo/the-typescript-functions-mental-model-1301
- https://www.youtube.com/watch?v=sswUBXaoXSI
from simple-markdown-editor-ts.
下記に関しては共通化しようと思ったメソッドはライブラリがイベントハンドラっぽく定義しておりそれを崩したくなかったので共通化は中止した。
#5 (comment)
from simple-markdown-editor-ts.
Related Issues (7)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from simple-markdown-editor-ts.