読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
読み込みの状態を、次のように書き直します。
type ProductsState =
| { status: "loading" }
| { status: "success"; products: Product[] }
| { status: "error"; message: string };
| 状態 | 持っているもの |
|---|---|
"loading" | なし |
"success" | 商品の一覧 |
"error" | エラーの文 |
3つの型はすべて status を持ち、その値がリテラル型で違っています。status を見れば、どの状態かが1つに決まります。このように、共通のプロパティの値で見分けられるユニオン型を、判別可能なユニオンと呼びます。status のように見分けるためのプロパティを、判別子と呼びます。
ありえない状態は、作れなくなります。
const s: ProductsState = { status: "loading", message: "失敗しました" };
Object literal may only specify known properties, and 'message' does not exist in type '{ status: "loading"; }'.
6 / 16