AI Hints
Home›TypeScript Tutorial›Object Types
TypeScript · Lesson 20 of 120

Optional Properties

Maybe there.

⏱ 2 min read▶ Video at 16:06🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Some properties aren't always there. A bike might have a discount, or not. A question mark after the name makes a property optional.

Optional Properties
From the video: Optional Properties
  • Not always there
  • A question mark
  • Optional

An optional discount

Discount is optional. Inside the function, it might be undefined, so we use two question marks to fall back to zero. Run it. Both bikes work, with and without a discount.

app.tstypescript
function finalPrice(bike: { price: number; discount?: number }) {
  return bike.price - (bike.discount ?? 0);
}

console.log(finalPrice({ price: 849.5 }));
console.log(finalPrice({ price: 849.5, discount: 50 }));
Output
849.5
799.5

Using it unchecked

Here we use the discount directly, without a fallback. Run it. TypeScript warns that it might be undefined.

app.tstypescript
function saving(bike: { price: number; discount?: number }) {
  return bike.discount * 2;
}
Output
app.ts line 2: 'bike.discount' is possibly 'undefined'.

Summary

A question mark makes a property optional, and you must handle it being missing. Next, readonly.

Key takeaways
  • discount?
  • ?? 0
  • Handle undefined
Next up: readonly — look, don't touch