困ったこと ユニオン型(合併型)を使って型宣言をするとき、以下のように書きたいことがあるかもしれません。 /** * typeofを使って任意の型の場合で条件分岐させる * UserTextEvent: キーボードによって操作された時の文字情報を保持しているイベント * UserMouseEvent: マウスの操作をした時のx軸y軸の情報を保持しているイベント */ type UserTextEvent = {value: string, target: HTMLInputElement} type UserMouseEvent = {value: [number, number], target: HTMLElement} type UserEvent = UserTextEvent | UserMouseEvent function handle(event: UserEvent) {
![【TypeScript】タグ付きユニオン型で型情報を正しく認識させる!](https://cdn-ak-scissors.b.st-hatena.com/image/square/d2e8e2e2cd48b797217c030a63a5c3b0fa2e8b7f/height=288;version=1;width=512/https%3A%2F%2Fres.cloudinary.com%2Fzenn%2Fimage%2Fupload%2Fs--HIfRwWof--%2Fc_fit%252Cg_north_west%252Cl_text%3Anotosansjp-medium.otf_55%3A%2525E3%252580%252590TypeScript%2525E3%252580%252591%2525E3%252582%2525BF%2525E3%252582%2525B0%2525E4%2525BB%252598%2525E3%252581%25258D%2525E3%252583%2525A6%2525E3%252583%25258B%2525E3%252582%2525AA%2525E3%252583%2525B3%2525E5%25259E%25258B%2525E3%252581%2525A7%2525E5%25259E%25258B%2525E6%252583%252585%2525E5%2525A0%2525B1%2525E3%252582%252592%2525E6%2525AD%2525A3%2525E3%252581%252597%2525E3%252581%25258F%2525E8%2525AA%25258D%2525E8%2525AD%252598%2525E3%252581%252595%2525E3%252581%25259B%2525E3%252582%25258B%2525EF%2525BC%252581%252Cw_1010%252Cx_90%252Cy_100%2Fg_south_west%252Cl_text%3Anotosansjp-medium.otf_37%3A%2525E3%252581%252595%2525E3%252581%252596%2525E3%252581%2525AA%2525E3%252581%2525BF%252Cx_203%252Cy_121%2Fg_south_west%252Ch_90%252Cl_fetch%3AaHR0cHM6Ly9zdG9yYWdlLmdvb2dsZWFwaXMuY29tL3plbm4tdXNlci11cGxvYWQvYXZhdGFyL2QzOTU3NDllYjguanBlZw%3D%3D%252Cr_max%252Cw_90%252Cx_87%252Cy_95%2Fv1627283836%2Fdefault%2Fog-base-w1200-v2.png)