Having the following code:
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'
}
Why can’t typescript infer that data
always exists if flag
is set to true
?
I know I can fix this by defining a return type for the function, but it’d be good if TS automatically infers it.