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