I have this Try it Yourself TypeScript Optional Chaining example from W3Schools TypeScript Null & Undefined section in screenshot below.
I can see that the purpose of the example is to show you that when data is undefined, it displays No Yard, but it is unclear to me why this is happening and how you can make it display Yard size is 500 sqft ?
My understanding is that this code below is using a new type (House interface), defining a variable called home and has sqft property with a value of 500.
let home: House = { sqft: 500 }
Code below is using an interface called House, that specifies property names along with it's types. It specifies sqft property as a number type and then it says yard? is an optional property and has a sqft property within it of number type.
interface House {
sqft: number;
yard?: {
sqft: number;
};
}
Now with the code below, this is where I am not sure why yard size is undefined and showing No yard.
function printYardSize(house: House) {
const yardSize = house.yard?.sqft;
if (yardSize === undefined) {
console.log('No yard');
} else {
console.log(`Yard is ${yardSize} sqft`);
}
}
My understanding is that the function is picking up properties and their types from House interface, using a variable const yardSize to pick up optional yard sqft. Finally it is using an if else statement to display the result
If someone can give me a good understanding on how it works both ways with an undefined No yard and and a value shown with Yard is 500 sqft, then that will be appreciated help, thanks ?