Take
Take

Reputation: 394

Why does TS let me return wrong type in overloaded function declarations?

I think the question is clear enough and here is the code that makes me wonder:

type T = {
  (value: number): number
  (value: string): string
}

First Example

const bar: T = (value: any) => {
  if (typeof value === "number") return []
  return value
}
bar(10) // []

For me it is inconsistent that the compiler then throws an error in the following example:

Second Example

const bar: T = (value: any) => {
  return []
}

Why can I return [] in the first example but get an error if I return [] in the second example?

Thank you!

Upvotes: 1

Views: 186

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 38046

If return type of the function is not specified (like in example above), typescript will infer the return type by creating union of possible return values' types.

So we have union of [] and any. Union of any type with whatever other type will result in any

type Result = any | []; // any

Playground

Now our function's signature resolved as (value: any) => any therefore assignment to variable of type T is allowed.

* This has nothing to do with overloads.

Upvotes: 1

Chris Heald
Chris Heald

Reputation: 62708

any opts out of type checking. By using it, you're effectively telling Typescript to not care about type checking for the code paths that use it.

When you return an any type (as you are with value), Typescript will skip checking if it matches the declared return type. However, when you return an explicit empty array (as in your second example), that is a known type, not an any, so Typescript can check if it matches the declared return type.

Upvotes: 3

Related Questions