読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
オブジェクトの型がいくつかあるとき、プロパティがあるかどうかでしぼりこめます。
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 Date | new で作る値か | Date、Error など |
中身に if (typeof price === "number") { return `${price}円`; } return price; と書きます。if の後では、price は string にしぼりこまれています。
8 / 17