Typescript - Tips & Tricks - Optional modifier

Full Stack Developer and JavaScript and TypeScript enthusiastic.
Search for a command to run...

Full Stack Developer and JavaScript and TypeScript enthusiastic.
No comments yet. Be the first to comment.
In this series, You'll see some tips and tricks using Typescript
Welcome back guys, today I'll speak about the "Index Signature". In some cases, we need to create some special types like dictionaries. These special types have some keys that identifies the elements and the datas. A simple example: export type User ...
Today, I wanna show you how to set up your devices with Antigravity using only the agentic mode, without touching any code. At the last CodeMotion Rome, I got my special badge. A CM Node, a special ha

As a developer, you have to take control of your projects every day. Whether it is a company repository, an open source project you maintain or collaborate on, or a simple pet project. Gaining control over your projects often depends on the platform ...

My Antigravity first experience

Write clear and insightful commit messages using AI and GitLens.

We are in the AI era. New models emerge daily, and many applications have already integrated AI into their workflows. Gemini, OpenAI, Copilot, Deepseek, Llama, and many others enable AI in your applications or help you write code, but they all need a...

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!