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.
2
Answers
maybe this code fix:
You can do this with
as const
or create a discriminated union around yoursuccess
property.Using
as const
:Using a union:
Why this happens is that just assigning
true
orfalse
, TypeScript infers that property to aboolean
so thedata: null
case, it can’t prove that{ success: true, data: null }
won’t happen. There’s also no type information thatflag
has to relate to the return type. That is where generics help.