DEV Community

Cover image for Typescript - Tips & Tricks - Optional modifier

Typescript - Tips & Tricks - Optional modifier

puppo profile image Luca Del Puppo ・1 min read

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: "",

const person2: Person = {
  name: "name2",
  surname: "surname2",
  email: "",
  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", "");
  Name: name1
printPerson("name2", "", "123");
  Name: name2
  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!

Discussion (0)

Editor guide