Ad space (banner)
Lesson 8 / 20

Optional Properties (?)

This lesson covers optional properties โ€” properties inside an interface that may or may not be present. It's for anyone searching "TypeScript interface optional."

Adding ? after a property name makes that property optional. When it's omitted, its value is treated as undefined.

The example makes a nickname (nickname) optional with interface Profile { name: string; nickname?: string; }, and shows a fallback message with a ternary operator when there's no value.

A common early mistake is accessing an optional property without checking for undefined first. When handling a property that "might or might not have a value," it's important to always build the habit of checking whether it exists.

In real projects, optional properties come up frequently when handling data with a lot of non-required fields, like a form submission.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)