For this simple guide, we will solve for JavaScript object optional property, by using a hypothetical Software Engineer model.
interface Engineer {
name: string;
/**
* other properties go here
*/
isFullStack?: boolean;
}
The Engineer can be a fullstack, and if they are not fullstack, then we don’t need to set it as false.
const isEngineerFullStack = () => {
/**
* Do some calculation here, but for now, we will return false
* just for the purpose of this demonstration.
*/
return false;
};
We have a simple method to check the status of whether Engineer is fullstack.
const engineer: Engineer = {
name: "Binge On Code",
...(isEngineerFullStack() ? { isFullStack: true } : {}),
};
console.log("engineer", engineer);
Now the most important part is:
...(isEngineerFullStack() ? { isFullStack: true } : {})
and what we are doing here is optionally spreading the Engineer object, and providing the isFullStack property, and on false, we are spreading an empty object.
console.log("engineer", engineer);
/**
* engineer { name: 'Binge On Code' }
*/
And that is it!
With optional property JavaScript object, you can be able to send only the needed payload to the backend, and use defaults on your backend for the missing values!