I came across this Try it Yourself TypeScript Optional Chaining example in W3Schools TypeScript Null & Undefined section, and I have attached a screenshot for reference.
https://i.sstatic.net/s8q1J.png
The example demonstrates that when data is undefined, it displays No Yard. However, I am curious to understand why this happens and how one can make it display Yard size is 500 sqft.
As per my understanding, the code provided defines a variable called home within a new type (House interface) with a property named sqft having a value of 500.
let home: House = { sqft: 500 }
The subsequent code introduces an interface called House, outlining property names along with their respective types. It specifies sqft as a number type and declares yard? as an optional property with a nested sqft property of number type.
interface House {
sqft: number;
yard?: {
sqft: number;
};
}
The following snippet is where confusion arises as to why yard size is undefined and displaying 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`);
}
}
From what I gather, the function leverages properties and types from the House interface, utilizing a constant variable yardSize to access the optional yard sqft value. Subsequently, it employs an if-else statement to output the result.
If anyone could provide me with a clear explanation on why it functions the way it does, both displaying No yard for undefined scenarios and Yard is 500 sqft for specified values, I would greatly appreciate the insight. Thank you!