TypeScript の 判別可能なユニオンファクトリー

レベル 5600 打鍵

ジェネリックな Action 型は、ペイロードの型が指定されたかどうかで { type } か { type, payload } を作ります。reducer は type で分岐し、TypeScript は各 case でどの payload があるかを把握します。

TypeScript のコード

// P の既定値は void で、「ペイロードなし」を意味する
1type Action<T extends string, P = void> = P extends void
// ペイロードなしなら type フィールドだけ
2 ? { type: T }
// ペイロードありなら type と P 型の payload
3 : { type: T; payload: P };
// { type: "LOADING" } になる
4type LoadingAction = Action<"LOADING">;
// 成功とエラーはペイロード付きのアクション
5type SuccessAction = Action<"SUCCESS", { data: string[] }>;
6type ErrorAction = Action<"ERROR", { message: string }>;
// type フィールドで判別する共用体
7type AppAction = LoadingAction | SuccessAction | ErrorAction;
8function reducer(action: AppAction): string {
// type を調べると各 case で action が絞り込まれる
9 switch (action.type) {
10 case "LOADING": return "Loading...";
// ここでは action は SuccessAction なので payload.data が使える
11 case "SUCCESS": return action.payload.data.join(", ");
// ここでは action は payload.message を持つ ErrorAction
12 case "ERROR": return action.payload.message;
13 }
14}
// ["a", "b"] を連結して「a, b」を表示する
15console.log(reducer({ type: "SUCCESS", payload: { data: ["a", "b"] } }));

実行結果

a, b
このコードでタイピング練習する

このコードでタイピング練習ができます。記録はランキングに反映されません。

このコードで使う記号

この TypeScript のコードで打つ記号と、出てくる回数です。

  • "× 22
  • :× 14
  • ;× 10
  • .× 10
  • {× 8
  • }× 8
  • ,× 6
  • =× 6
  • (× 5
  • )× 5

TypeScript のレベル 5 のほかのコード例

← TypeScript タイピング練習のトップへ