To avoid undefined values when using or accessing the optional object properties, the basic idea is to check the property value using an if conditional
statement or the optional chaining operator
before accessing the object property in TypeScript.
TL;DR
// object type declaration
let personDetails: {
name: string;
age?: number;
};
// object
personDetails = {
name: "John Doe",
};
// Solution 1: ✅
// check if the 'age' property exists in the
// 'personDetails' object before accessing it
// using an if statement conditional check
if (personDetails.age) {
const age = personDetails.age;
}
// Solution 2: ✅
// check if the 'age' property exists in the
// 'personDetails' object before accessing it
// using optional chaining operator in TypeScript
const age = personDetails?.age || "No age value is supplied";
To understand it better let's make an object called personDetails
with 2 properties called name
(string type) and age
(number type) where the age
property is an optional property. it can be done like this,
// object type declaration
let personDetails: {
name: string;
age?: number;
};
// object
personDetails = {
name: "John Doe",
};
Now the object personDetails
is valid and is allowed to be executed by the TypeScript compiler since the age
property is optional.
Now let's try to access the value of the age
property before the value is set.
It can be done like this,
// object type declaration
let personDetails: {
name: string;
age?: number;
};
// object
personDetails = {
name: "John Doe",
};
// try to access the 'age' property
// in the personDetails object
const age = personDetails.age; // 🤯 undefined
As you can see from the above code, the value of the age
property is undefined
because the value is not set which may crash our program during the runtime or results in invalid values.
Typescript allowed us to access the age
property since it is an optional property and Typescript assumed that we know what we are doing.
Now to avoid this issue we can either use conditional check using an if statement
or use the optional chaining operator
like this,
// object type declaration
let personDetails: {
name: string;
age?: number;
};
// object
personDetails = {
name: "John Doe",
};
// Solution 1: ✅
// check if the 'age' property exists in the
// 'personDetails' object before accessing it
// using an if statement conditional check
if (personDetails.age) {
const age = personDetails.age;
}
// Solution 2: ✅
// check if the 'age' property exists in the
// 'personDetails' object before accessing it
// using optional chaining operator in TypeScript
const age = personDetails?.age || "No age value is supplied";
As you can see from the above code we have corrected our code from being resulting in undefined
values if the age
property is not set.
See the execution of the above code live in codesandbox.
That's all 😃!