読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第2節 型の絞り込み

2.3 in と instanceof

オブジェクトの型がいくつかあるとき、プロパティがあるかどうかでしぼりこめます。

type StoreNotice = { message: string };
type ClosedNotice = { message: string; reopenAt: string };

const showNotice = (notice: StoreNotice | ClosedNotice): string => {
  if ("reopenAt" in notice) {
    // ここでは notice は ClosedNotice
    return `${notice.message}(再開:${notice.reopenAt})`;
  }
  return notice.message;
};

"reopenAt" in notice は、「notice に reopenAt というプロパティがあるか」を調べます。

instanceof は、Date や Error のように、new で作る値かどうかを調べます。

try {
  await loadProducts();
} catch (error) {
  // error は unknown
  if (error instanceof Error) {
    console.error(error.message);
  }
}

catch で受け取る error は、何が投げられたか分からないため unknown です。instanceof Error で確かめると、message を読めます。

書き方調べること向いている値
typeof x === "string"基本の型の種類文字列、数など
"key" in xプロパティがあるかオブジェクトの型が複数あるとき
x instanceof Datenew で作る値かDate、Error など
解答の例

中身に if (typeof price === "number") { return `${price}円`; } return price; と書きます。if の後では、price は string にしぼりこまれています。

8 / 17