Consider the following code snippet:
const foo = (flag: boolean) => {
if (flag) {
return {
success: true,
data: {
name: "John",
age: 40
}
}
}
return {
success: false,
data: null
}
}
const result = foo(true);
if (result.success) {
console.log(result.data.name); // TS error: 'result.data' is possibly 'null'
}
What prevents TypeScript from recognizing that data
always exists when flag
is set to true
?
In this scenario, it would be beneficial if TypeScript could automatically infer the existence of data
without requiring an explicit return type definition for the function.