Reputation: 394
I think the question is clear enough and here is the code that makes me wonder:
type T = {
(value: number): number
(value: string): string
}
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:
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
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
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
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