DEV Community

Cover image for Typescript - Tips & Tricks - Optional modifier
Luca Del Puppo for This is Learning

Posted on • Edited on

3 3

Typescript - Tips & Tricks - Optional modifier

Hi guys and welcome back,
Today I'll talk about the optional modifier.
Sometimes we have objects that have some optional properties.
In these cases, we need to identify the optional and the required properties, so the consumers can know what is required and what not.
To do this in typescript we have a special modifier named "optional" and it is identified by a question mark (?).
Let's see an example:

export type Person = {
  name: string;
  surname: string;
  email: string;
  phone?: string;
};

const person1: Person = {
  name: "name1",
  surname: "surname1",
  email: "email1@email1.it",
};

const person2: Person = {
  name: "name2",
  surname: "surname2",
  email: "email2@email2.it",
  phone: "123",
};
Enter fullscreen mode Exit fullscreen mode

In this example we can see the optional modifier in action, the "phone" property is marked as optional so in the "person1" object we can avoid setting the "phone" property.
This modifier, also, could be used in the functions' parameters if we have one or more optional parameters.
A simple example.

function printPerson(name: string, email: string, phone?: string): void {
  console.log(`Name: ${name}`);
  console.log(`Email: ${email}`);
  if (phone) console.log(`Phone: ${phone}`);
}

printPerson("name1", "email1@email1.it");
/*
  Name: name1
  Email: email1@email1.it
*/
printPerson("name2", "email2@email1.it", "123");
/*
  Name: name2
  Email: email2@email1.it
  Phone: 123
*/
Enter fullscreen mode Exit fullscreen mode

We can see how in the first example we can avoid setting the phone parameter because it's optional.

From the optional modifier, it's all.
See you soon guy!

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

AWS Security LIVE! Stream

Go beyond the firewall

There's more to security than code. Explore solutions, strategies, and the full story on AWS Security LIVE!

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay