読み方のヒント

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

第2節 省略できる項目と読み取り専用

2.1 ? で省略できる項目

予約の型に、省略できる備考を加えます。

type Reservation = {
  id: string;
  name: string;
  pickupAt: string;
  items: ReservationItem[];
  note?: string;
};

const r1: Reservation = {
  id: "R-0001",
  name: "田中",
  pickupAt: "2026-11-02 08:00",
  items: [
    { productId: "p001", quantity: 1 },
    { productId: "p002", quantity: 2 },
  ],
};

note?: string の ? は、「このプロパティはなくてもよい」という意味です。r1 には note がありませんが、エラーになりません。

省略できる項目を読むと、型は string | undefined になります。

console.log(r1.note.length);
'r1.note' is possibly 'undefined'.

ないかもしれない値は、あるかどうかを確かめてから使います。

if (r1.note !== undefined) {
  console.log(r1.note.length);
}

const noteText = r1.note ?? "(なし)";

?? は、左の値が null か undefined のときに、右の値を使う書き方です。

6 / 16