#Return type after assign to a const is different to return type without assign?

11 messages · Page 1 of 1 (latest)

unkempt marlin
#

I have the following code where the return type of the function a is inferred to be {a?: undefined} | {a: number}, and the return type of the function b is inferred to be {}. Can someone explain why, and if I can get TypeScript to infer what I believe is the more correct type in the second case?

function a() {
  if (Math.random()) {
    return {};
  }
  return {a: 0};
}

function b() {
  if (Math.random()) {
    return {};
  }
  const t: {a: number} = {a: 0};
  return t;
}
sharp sentinelBOT
#
extracraftx#0

Preview:```ts
function a() {
if (Math.random()) {
return {}
}
return {a: 0}
}

function b() {
if (Math.random()) {
return {}
}
const t: {a: number} = {a: 0}
return t
}```

wooden skiff
#

is there a reason you don't want to annotate the return type? i wouldn't rely on inference in this case since you care about the specific type

unkempt marlin
#

Yes, this is just a minimal example with two branches, but my actual function is going to be at least a couple more branches with more complex objects, so I would like to avoid explicitly specifying the return type

#

In any case, I feel this behaviour is odd right? There's no actual difference in the types of the return statements

#

Also this infers how I would expect:

function b() {
  if (Math.random()) {
    return {a: 0};
  }
  const t = {a: 0, b: ''};
  return t;
}
wooden skiff
#

i think in a the fact that the value is being returned can be used while inferring a type for the value {a: 0} (and that in turn can feed back to affect the overall return type). in b there's already a type for the returned value, TS sees that it's assignable to {} (the contextually-determined return type at that moment), and therefore doesn't narrow {}

#

just a guess though. you'd have to dig through the implementation to be sure. type inference works in mysterious ways

wooden skiff
unkempt marlin
tulip radish
#

@unkempt marlin Compiler internals channel, or a github issue is probably the best way to get the attention of someone who knows about that. If you want to pester them over it that is.