読み方のヒント

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

第1節 オブジェクトの型

1.2 余分なプロパティ

型にないプロパティを書いても、エラーになります。

const melonpan: Product = {
  id: "p005",
  name: "メロンパン",
  price: 200,
  category: "pastry",
  reservable: true,
  color: "yellow",
};
Object literal may only specify known properties, and 'color' does not exist in type 'Product'.
状態結果
必要なプロパティがないis missing のエラー
型にないプロパティがあるdoes not exist in type のエラー
プロパティの型が違うis not assignable to のエラー

余分なプロパティのエラーは、{ } で直接値を書いたときに出ます。打ちまちがいで reservabel と書いたときにも、このエラーで気づけます。

解答の例

type ReservationItem = { productId: string; quantity: number; }; を作り、const item: ReservationItem = { productId: "p002", quantity: 2 }; と書きます。

3 / 16