Typescript - Tips & Tricks - Optional modifier

Hi guys and welcome back, Today I'll talk about the optional modifier. Sometimes we have objects that...

#typescript#webdev
Luca Del PuppoLuca Del Puppo
Article Series · Part 8 of 21TypeScript - Tips & Tricks
View full series (21)
  1. #7Previous
    any vs. unknown
  2. #8Reading now
    Optional modifier
  3. #9Up next
    Index Signature
Browse all 21 parts in this series
  1. #1typeof
  2. #2Literal Types
  3. #3keyof
  4. #4Union and Intersection
  5. #5Overloaded Functions
  6. #6this parameter
  7. #7any vs. unknown
  8. #8Optional modifierCurrent
  9. #9Index Signature
  10. #10readonly modifier
  11. #11Readonly Array
  12. #12Tuple
  13. #13Non-null assertion operator
  14. #14Never type
  15. #15Assert Function
  16. #16Type Guard
  17. #17Conditional Type
  18. #18infer keyword
  19. #19Mapped Types
  20. #20Advanced Types
  21. #21Rest Parameters & Rest Arguments

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",
};

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
*/

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!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.