読み方のヒント

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

第3節 strict のほかに使う設定

3.2 exactOptionalPropertyTypes

省略できるプロパティ note?: string には、ふだんの設定では undefined をわざと入れることもできます。exactOptionalPropertyTypes を有効にすると、これがエラーになります。

type Reservation = {
  id: string;
  note?: string;
};

const r: Reservation = { id: "R-0001", note: undefined };
Type '{ id: string; note: undefined; }' is not assignable to type 'Reservation' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
書き方意味この設定が有効のとき
note?: stringプロパティがないことがあるundefined を入れるとエラー
note?: string | undefinedないことも、undefined のこともあるエラーにならない

「書かれていない」と「undefined が入っている」を区別したいときに役立ちます。区別がいらないプロパティには、型に | undefined を足します。

13 / 20