DEV Community

Cover image for Optional Properties in TypeScript
Bridget Amana
Bridget Amana

Posted on

Optional Properties in TypeScript

In TypeScript, optional properties are a way to say, “This part of the information might not always be there.” Imagine you're filling out a form where some fields are optional—like a middle name on a job application. You might include it, or you might leave it blank. Optional properties in TypeScript work similarly.

What Are Optional Properties in TypeScript?

Optional properties are parts of an object that don’t always have to be filled in. If you’re creating an object with TypeScript, you can mark some properties as optional so that you don’t have to include them every time you create the object.

How to Define Optional Properties

In TypeScript, you can mark a property as optional by adding a question mark (?) after the property name in the type definition. Here’s a clear example:

Example:

function userName(obj: { first: string; last?: string }) {
  // ...
}

// Both won't throw any error
userName({ first: "Bob" });
userName({ first: "Alice", last: "Alisson" });
Enter fullscreen mode Exit fullscreen mode

In this example:

  • first is a required property. You must include it whenever you use userName.
  • last is an optional property. It can be included or omitted based on your needs.

Benefits of Using Optional Properties

Using optional properties in TypeScript provides several advantages:

  • Flexibility: Allows you to create objects with varying structures without needing multiple types.
  • Clarity: Makes it clear which properties are essential and which are not.
  • Adaptability: Helps in scenarios where not all information is available or relevant.

Another example

Imagine a contact card where:

  • Name is always required.
  • Middle Name and Phone Number are optional.

In TypeScript, this can be represented as:

interface ContactCard {
  name: string; // This is required
  middleName?: string; // This is optional
  phoneNumber?: string; // This is optional
}
Enter fullscreen mode Exit fullscreen mode

You can create a contact card with just the name:

const contact1: ContactCard = { name: "John Doe" };
Enter fullscreen mode Exit fullscreen mode

Or include additional optional details:

const contact2: ContactCard = { name: "Jane Doe", middleName: "A.", phoneNumber: "123-456-7890" };
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding and using optional properties in TypeScript allows you to write more flexible and maintainable code. By marking certain properties as optional, you can accommodate various scenarios and requirements without cluttering your code with unnecessary types.

Stay tuned for the next article in our TypeScript series, where we’ll explore more about TypeScript types to help you 🫵 build even better applications!

Top comments (0)