Check out this TypeScript code snippet for a quick example.
// Setting up the example
declare var data:{info?: {details: string}};
function instant(callback: () => void) {
callback();
}
// Safeguarding the data
if (data.info) {
console.log(data.info.details); // ✅ This works!
instant(() => {
console.log(data.info.details); // ❌ TypeScript error : 'data.info' may be 'undefined'.(18048)
});
}
The type guard for data.info
ensures it is not null, and infers its type as {details: string}
.
But why does TypeScript throw an error in the immediate callback function, warning that data.info
might be undefined? What's causing this issue?