To make object properties optional, we can declare the variable name, followed by the :
symbol (colon), followed by the {}
symbol (Open and close curly brackets). Inside the brackets, we can define the name of the property followed by the ?
(question mark) and :
(colon) symbol, and finally the type of property to make it an optional object property in TypeScript.
To end the type declaration we can either use the ;
symbol (semi-colon) or the ,
symbol (comma).
TL;DR
// simple object
// with types added for each property
// and an optional age property
let personDetails: {
name: string;
age?: number;
};
// This is allowed ✅
// we can omit the value for the age property
// and TypeScript won't show us an error
personDetails = {
name: "John Doe",
};
For example, let's say we have an object called personDetails
having 2 properties called name
and age
like this,
// simple object
const personDetails = {
name: "John Doe",
age: 23,
};
As you can see from the above code, the name
property has a value called John Doe
and the age
property has a value called 23
but we don't need to have a value for the age
property which means the age
property is optional.
To make an object property optional, it can be done like this,
// simple object
// with types added for each property
// and an optional age property
let personDetails: {
name: string;
age?: number;
};
Now let's try to add the required property name
and the optional property age
values like this,
// simple object
// with types added for each property
// and an optional age property
let personDetails: {
name: string;
age?: number;
};
// This is allowed ✅
personDetails = {
name: "John Doe",
age: 23,
};
// This is also allowed ✅ ✅
// we can omit the value for the age property
// and TypeScript won't show us an error
personDetails = {
name: "John Doe",
};
As you can see that TypeScript won't show us an error if don't supply the age
property which is the functionality we want.
See the execution of the above codes live in codesandbox.
That's all 😃!