dariofarzati
dariofarzati

Reputation: 8646

Why does TypeScript not automatically use literal types when inferring the return type of a function?

Considering the following snippets:

//
// Case 1: return type is { statusCode: number }
//
export const handler = () => {
  return {
    statusCode: 200
  }
}

//
// Case 2: return type is { statusCode: 200 }
//
export const handler = () => {
  return {
    statusCode: 200 as const
  }
}

Since the function will always return the same value (no alternative flows), it seems to me the second case should be the default. Or, in other words, I think TypeScript should always try to be as specific as possible by default.

Why do I need to manually specify the return type, or use as const?

Upvotes: 4

Views: 60

Answers (1)

Playturbo
Playturbo

Reputation: 91

The field statusCode is mutable on the returned object. Thus, if changed, the type would no longer be the same which breaks type safety.

let obj = handler();
obj.statusCode = 404; // This is allowed but breaks the type { statusCode: 200 }

Upvotes: 3

Related Questions